Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

c# - DataGridView RowFilter By Date

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. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...