Compare date value obtained from TextBox in Windows Form, to Date value stored in Excel sheet
I am trying to make date comparisons between a textbox value accepting date and a date type in Excel. Problem is direct string comparisons dont seem to work.I need to select only those rows from excel file where date is lesser than date specified by Eindows forms textBox. Any help would be greatly appreciated. My code snippet:
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Dat开发者_JS百科a Source=C:\\empdetails.xls;Extended Properties=ImportMixedTypes=Text;Excel 8.0;HDR=Yes;IMEX=1;";
OleDbDataAdapter adap = new OleDbDataAdapter("Select * from [Sheet1$] where Date < "+ txtDate.Text + "", connStr);
DataTable viewemployees= new DataTable();
adap.Fill(viewemployees);
dataGridView1.DataSource=viewemployees;
Date
is a named column accepting values of date type in Excel. Format: mm/dd/yyyy.
txtDate
is a textbox accepting values of same date format.
How do I use formulas in a query against Excel? Not sure about it but I think that DateValue may be of some help here?
Had a problem similiar to yours, I've been able to solve it with these Data type mismatch in criteria expression | Access, OleDb, C# answers.
In short terms, you have just to do this:
String sql = "select * from [Tabelle1$] WHERE blahblah "' AND (StartDate <= @curDate AND EndDate >= @curDate)";
OleDbCommand olDbCmd = new OleDbCommand(sql, con);
OleDbParameter curDate = new OleDbParameter("curDate", DateTime.Now);
curDate.DbType = DbType.DateTime;
olDbCmd.Parameters.Add(curDate);
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(olDbCmd);
This should solve the type-mismatches...
I reckon you need to use sql to compare both dates.
And i think you omitted the quote for the date you got from the textbox.
see a slightly modified version of your code below.
string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\sample.xls;Extended Properties=ImportMixedTypes=Text;Excel 8.0;HDR=Yes;IMEX=1;";
OleDbDataAdapter adap = new OleDbDataAdapter("Select * from [Sheet1$] where Date < '"+txtDate.Text+"'", connStr);
DataTable viewemployees= new DataTable();
adap.Fill(viewemployees);
dataGridView1.DataSource=viewemployees;
I hope this helps.
精彩评论