vb.net bindingsource filter cast date to string

£可爱£侵袭症+ 提交于 2019-12-11 23:19:04

问题


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

回答1:


I got it, and it works

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



回答2:


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.



来源:https://stackoverflow.com/questions/4390152/vb-net-bindingsource-filter-cast-date-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!