Sunday, 14 December 2008

DataTable Filtering Gotcha

The mission – if you choose to accept it is to filter a .Net DataTable to return results from a year or more ago. The code is
DataTable dtDataTable = GetDataTableMethod()

//.. limit the dataset
DataView dvDataTable = new DataView(dtDataTable);
dvSurveyList.RowFilter = "DateField < '" + DateTime.Now.AddYears(-1) + "'";
Our spies tell us that it doesn’t actually work. Agent tech splurge what is the solution? Stand well back folks while I insert the missing line.
DataTable dtDataTable = GetDataTableMethod()
dtDataTable.Locale = CultureInfo.CurrentCulture;

//.. limit the dataset
DataView dvDataTable = new DataView(dtDataTable);
dvSurveyList.RowFilter = "DateField < '" + DateTime.Now.AddYears(-1) + "'";
To me this makes sense. If you’re playing with dates then you’ll need the culture information – dates being different in different cultures. The odd thing is that the first set of code worked perfectly – until it stopped working. I have to confess I still don’t know why.

No comments: