My Code is as follows:
I am using:
date=datatype=date;
time=datatype=time;
private void button8_Click(object sender, EventArgs e)
{
//cmd = new SqlCommand("select * from Client_Attendence where date='" +dateTimePicker1.Value + "'", con);
DateTime dt1= Convert.ToDateTime((dateTimePicker1.Value));
DateTime dt2 = Convert.ToDateTime((dateTimePicker3.Value));
SqlDataAdapter sdf = new SqlDataAdapter("select * from Client_Attendence where date between '" + dt1+ "'and '"+dt2+"'", con);
DataTable sd = new DataTable();
sdf.Fill(sd);
dataGridView1.DataSource = sd;
//dataGridView1.Columns["balance"].DefaultCellStyle.BackColor = Color.Yellow;
//dataGridView1.Columns["enddate"].DefaultCellStyle.BackColor = Color.Red;
}
Convert the datetime to string first might help
dt1.ToShortDateString()
dt2.ToShortDateString()
You need to convert the DateTime
value to String
,
DateTime dt1= Convert.ToDateTime(dateTimePicker1.Value.ToString());
DateTime dt2 = Convert.ToDateTime(dateTimePicker3.Value.ToString());
Few things I must suggest here considering your following query:
SqlDataAdapter sdf = new SqlDataAdapter("select * from Client_Attendence where date between '" + dt1+ "'and '"+dt2+"'", con);
Fixes required in above query:
[date]
instead of date
and
. Suggestions
SqlParameters
instead of string concatination of dates in sql. SqlCommand
and pass it to SqlDataAdapter
. Suggestion 1 will avoid Sql Injection attack.
How to achieve 2? Use this link from MSDN
If the code you posted is a copy/paste, you have no space between dt1 and the word "AND".
"select * from Client_Attendence where date between '" + dt1+ "'and '"+dt2+"'"
needs to be
"select * from Client_Attendence where date between '" + dt1+ "' and '"+dt2+"'"
Also double check the format of your datetime objects. Depending on how they are represented in the strings you may need to define your Convert function more like this:
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture)
substitute your variable for the actual date and time and change the yyy-MM-dd format to match the format of your input.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.