How can I filter a DataColumn on a TimeSpan value?
Programming in C#.NET. I have a DataTable
with a column named Time which is of type System.TimeSpan
. When I display the DataTable
in a Da开发者_开发知识库taGridView
I want to filter out all the entries that don't have a time listed. I have tried the following but to no avail. Can you help?
DataView myDataView = new DataView(SomeDataTable);
myDataView.RowFilter += "Time >= 1"; // doesn't work
myDataView.RowFilter += "Time >= #00:00:01#"; // doesn't work
myDataView.RowFilter += "Time <> ''"; // doesn't work
myDataView.RowFilter += "Time <> ''"; // doesn't work
I found it...
myDataView.RowFilter = "Convert(Time, System.String) <> ''";
If someone bump into this annoying problem, unfortunately there is no good solve.
It seams that filter DataTable
with System.TimeSpan
is not working.
The solution I use is to change the type of the column in the SQL to NVARCHAR(8)
from Time(0)
(or whatever) and then you can just apply logic upon it like so:
StringBuilder builder = new();
// IsNull() is my own string extension
if (!ExecutionTimeFrom.IsNull())
{
builder.Append($"AND TimeStamp >= '{ExecutionTimeFrom}' ");
}
if (!ExecutionTimeTo.IsNull())
{
builder.Append($"AND TimeStamp <= '{ExecutionTimeTo}' ");
}
Afterward convert string from the sql table from hh:mm:ss
(10:32:15) back into System.TimeSpan
is as easy as:
bool isTimeSpan = TimeSpan.TryParse(TimeFromSql, out TimeSpan time);
I break my head on this for two days, I hope it will help :)
精彩评论