I tried this code:
(datagridview1.DataSource as DataTable).Select("date_time=" + Convert.ToDateTime(dtpDate.Text.ToString()));
but I thinks it still include the time and gets me error “Syntax error: Missing operand after ’12’ operator.”
What I really want to happen is that filter the datetime field of datable disregarding the time of it, just the date.
Here is what my datagridview looks like:
1 1 1/24/2013 12:34 AM
1 2 1/24/2013 12:34 AM
2 3 1/24/2013 12:53 AM
3 1/25/2013 12:30 AM
4 1/25/2013 12:53 AM
5 4 1/25/2013 2:10 AM
6 5 1/25/2013 2:26 AM
7 6 1/25/2013 2:39 AM
8 7 1/25/2013 2:40 AM
Updated code:
datagridview1.DataSource = (datagridview1.DataSource as DataTable).AsEnumerable()
.Where(r => r.Field<DateTime?>("date_time").HasValue
&& r.Field<DateTime?>("date_time").Value.Date == dt.Date).CopyToDataTable();
Don’t use strings when you want to compare dates. You can use
Linq-To-DataTableand the strongly typedDataRowextension methodField. Then use theDateproperty ofDateTime.Edit (according to your comment)
Then you have
nullsin this field. Since theFieldmethod supports nullable-types you can use it directly.Edit So you get an exception when the table is empty. Yes,
CopyToDataTablethrows anInvalidOperationExceptionwhen the source table is empty.Note that perhaps you don’t need to copy the result into a new
DataTableat all. You could bind the query itself to the datasource property of the datagridview, so try to simply omit theCopyToDataTable.Otherwise you could also check if the query returns anything: