DataGridView RowFilter By Date

本小妞迷上赌 提交于 2019-12-13 08:11:38

问题


My dataGridView_flaggedComments has, let say, 10 rows. Value in the Comments_Date column's cell shows dates in the format of 31/12/2014 12:01 PM, if I choose a date (which is without time portion) from comboBox_stockDates (e.g. 31/12/2014), I want it to filter (and display) all the rows that have 31/12/2014 xx:xx xx.

The below code would yield zero result even when the selected date (e.g. 31/12/2014) matches the rows which contain 31/12/2014 xx:xx xx. Any idea what has gone wrong here?

string dtFilter = string.Format("Comments_Date = #{0}#", comboBox_stockDates.SelectedItem.ToString());
(dataGridView_flaggedComments.DataSource as DataTable).DefaultView.RowFilter = dtFilter;

Alternatively, is there a way to convert both dates to string then compare? I tried to use LIKE operator but error says cannot be used to compare between DateTime and String.

Any help and guidance would be much appreciated! Thank you. :)


回答1:


I've got this fixed, so I propose my own answer. It might be of helpful in the future for someone who's looking for similar question.

string str = comboBox_stockDates.SelectedItem.ToString();
DateTime date = DateTime.ParseExact(str, "dd/MM/yyyy", CultureInfo.GetCultureInfo("en-GB"));
string dtFilter = string.Format(
    "[Comments_Date] >= '{0} 12:00:00 AM' AND [Comments_Date] <= '{0} 11:59:59 PM'", date.ToString("dd/MM/yyyy"));
(dataGridView_flaggedComments.DataSource as DataTable).DefaultView.RowFilter = dtFilter;


来源:https://stackoverflow.com/questions/26855493/datagridview-rowfilter-by-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!