I need to compare today's date with dates in Excel so that it displays all data entered today in DataGridView. I have tried many code iterations but continue to receive errors and some do not show required result. Here is the code:
private void todayToolStripMenuItem_Click(object sender, EventArgs e)
{
int day = todaysDate.Day ;
int month =todaysDate.Month;
MessageBox.Show("Month" + month+ "Date" + day, "abc", MessageBoxButtons.OK);
int year = todaysDate.Year;
String name = "Sheet1";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] WHERE Date CONTAINS " + day + "AND Date CONTAINS " + month +
"AND Date CONTAINS " + year, con);
try
{
con.Open();
}
catch (Exception)
{
}
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
Thanks in advance.
UPDATED Use query with parameters instead of injecting value into the string. This is working fine for me:
OleDbCommand oconn = new OleDbCommand("Select * From [Sheet1$] WHERE Date = @date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("@date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
connection.Close();
}
catch (Exception)
{
}