简体   繁体   中英

How to filter datetime field in datatable disregarding the time value of it in C#

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-DataTable and the strongly typed DataRow extension method Field . Then use the Date property of DateTime .

DateTime  dt = DateTime.Parse(dtpDate.Text);
DataTable filteredRows = table.AsEnumerable()
    .Where(r => r.Field<DateTime>("date_time").Date == dt.Date)
    .CopyToDataTable();

Edit (according to your comment)

"Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type.

Then you have nulls in this field. Since the Field method supports nullable-types you can use it directly.

DataTable filteredRows = table.AsEnumerable()
    .Where(r => r.Field<DateTime?>("date_time").HasValue 
            &&  r.Field<DateTime?>("date_time").Value.Date == dt.Date)
    .CopyToDataTable();

Edit So you get an exception when the table is empty. Yes, CopyToDataTable throws an InvalidOperationException when the source table is empty.

Note that perhaps you don't need to copy the result into a new DataTable at all. You could bind the query itself to the datasource property of the datagridview, so try to simply omit the CopyToDataTable .

var filteredRows = table.AsEnumerable()
    .Where(r => r.Field<DateTime?>("date_time").HasValue 
            &&  r.Field<DateTime?>("date_time").Value.Date == dt.Date);

datagridview1.DataSource = filteredRows;

Otherwise you could also check if the query returns anything:

DataTable table = new DataTable();
if(filteredRows.Any())
{
    table = filteredRows.CopyToDataTable();
}
            DataView dv = new DataView(Datatable1);
            dv.RowFilter = "StartDate >= #" + DtpDateRangeFrom.Value + "# AND StartDate <= #" + DtpDateRangeTo.Value + "#";

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM