CrazyPenguin
CrazyPenguin

Reputation: 649

vb.net bindingsource filter cast date to string

I'm using the filter method of Binding source in VB.net to filter results in a DataGridView based on the text in a search box. However, the idea of this search, is that it shows a row if any of the cells contain the text. So my filter string ends up looking like this:

filter = "ProductId LIKE '%" & searchterm & "%'" & " OR ScanDate like '%" & searchterm & "%'"

However, when I try to put the filter in the filter property, it complains, saying that it cannot convert the date column to text for the comparison.

Is there a way to tell the filter to cast the datetime cells to string?

What I'm considering doing is having a hidden column in the dataset that contains a casted version of the date, and I'll tell the filter to filter that column.

Here's my assign code:

bindingSource.Filter = filter 
dgv.DataSource = bindingSource.DataSource

Upvotes: 1

Views: 9762

Answers (2)

CrazyPenguin
CrazyPenguin

Reputation: 649

I got it, and it works

bindingSource.Filter = "ProductId LIKE '%" & searchterm & "%' OR Convert( ScanDate, 'System.String') LIKE '%" & searchterm & "%'"

Upvotes: 4

Neil Knight
Neil Knight

Reputation: 48567

You should break down your filter code. So, rather than setting your filter code all in one line, I would run a test on the searchterm to see if it is a valid DateTime. Then, you can change your filter accordingly because I don't think you'll have a ProductId which is like a DateTime.

try
{
    string dt = DateTime.Parse(searchterm).ToString();
    filter = "ScanDate like '%" & searchterm & "%'"
}
catch
{
    filter = "ProductId LIKE '%" & searchterm & "%'"
}

Sorry for the C# code, but it should be straight forward to convert to VB.Net.

Upvotes: 0

Related Questions