Reputation: 3080
Updated:
I am trying to filter a DataTable based on a particular date. My datatable has a column "whn" which contains dates. A Sample date from the DataTable:
{21/02/2012 10:03:53} object {System.DateTime}
Here is the code I am using to try and filter the DataTable:
String datevalue= "21/02/2012 10:03:53";
DataRow[] foundRows;
foundRows = dttemp.Select(String.Format("whn = '{0}'", datevalue));
However this does not work and returns 0 rows. Even though I know that a row containing the date in "datevalue" exists.
Unsure why this is not working, any help is appreciated.
Thanks.
Upvotes: 3
Views: 16886
Reputation: 124814
If you want to exactly match the supplied DateTime, including fractions of a second, you should use a DateTime format that has enough precision. Probably the round-trip format ("o") is a good bet:
foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn = '{0:o}'", datevalue));
However, it's more likely you want to match values that fall into a range. For example, if you want all values that have the same date, but any time of day, you could use:
foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn >='{0:o}' AND whn < '{1:o}'",
datevalue.Date, datevalue.AddDays(1).Date));
Similarly if you want all values that are in the same second (but may have fractions of a second), you can use:
DateTime from = dttemp.AddTicks( - (dttemp.Ticks % TimeSpan.TicksPerSecond));
foundRows = dttemp.Select(String.Format(dttemp.Locale, "whn >='{0:o}' AND whn < '{1:o}'",
from, from.AddSeconds(1)));
The call to AddTicks truncates the supplied DateTime to a whole number of seconds, as described in the accepted answer to this StackOverflow question.
Note I used dttemp.Locale
to use the correct locale (CultureInfo) in case your DataTable has a locale other than your current culture.
Upvotes: 7
Reputation: 131
foundRows = dttemp.Select("whn LIKE '{0}'",datevalue);
should probably be
foundRows = dttemp.Select(String.Format("whn LIKE '{0}'",datevalue));
more info here http://www.csharp-examples.net/dataview-rowfilter/
Upvotes: 2
Reputation: 26406
Use =
instead of LIKE
foundRows = dttemp.Select(String.Format("whn = '{0}'", datevalue));
Upvotes: 1