简体   繁体   中英

How to filter date values in datagrid

I can't filter a date value in my datagrid. Here is my code:

DataTable dbdataset;
DataView DV = new DataView(dbdataset);
DV.RowFilter = string.Format("Data LIKE '%{0}%'", textBox1.Text);
dataGridView1.DataSource = DV;

I always get this error:

Unable to Perform Operation 'Like' on System.DateTime and System.String

Please can someone help me?

You cannot use the LIKE operator on DateTime Data Type. Try using the equal operator.

DV.RowFilter = string.Format("Data = '{0}'", textBox1.Text);

But, be careful of what's inside textBox1.Text . It must be convertible to a DateTime Data Type. Remember also that DateTime has a Time part also, not just a Date part.

Or you may want to try this to filter all rows in a specific day:

DateTime dt = Convert.ToDateTime(textBox1.Text);
DV.RowFilter = string.Format("Data > '{0}' AND Data < '{1}'", dt.AddDays(-1).ToString("yyyyMMdd"), dt.AddDays(1).ToString("yyyyMMdd"));

Obviously field Data is from type Datetime and you can not perform Like on it. You can use:

DV.RowFilter = string.Format("Data = '{0}'", textBox1.Text);

Also you have possibility with =, >=, <=.

Also please change the field name to Date !

You can try something like that in LINQ

CultureInfo invC = CultureInfo.InvariantCulture;

var query= from myRow in dataTable.AsEnumerable()
                     where myRow.Field<DateTime>("Date").ToString(invC).Contains("mm/dd/yyyy")
                    select myRow;

// the date should be in format months/days/year -> Example 23 January 2014 is 01/23/2014

DataTable newTable= query.CopyToDataTable<DataRow>();

DV.RowFilter = string.Format("Data >= '{0}'", textBox1.Text); will work if your column is a datetime in the database. This will return records at or newer than the specified date. Switch the sign to < if you're looking for records older than that date.

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