简体   繁体   中英

SQL database: search more than one column

I got this code which works fine:

DataView dv = new DataView(bazaDataSet.tbl_baza);

if (listBox1.SelectedIndex == 0)     
{
     dv.RowFilter = string.Format("Name LIKE '%{0}%'", txtSearchData.Text);
     dataGridView1.DataSource = dv;
}

but I'm trying to search more than one column, and I can't get it to work for me. At the end I want user to be allowed to choose more then one item from listBox and search database regarding that choice.

You can build up strings that can be used in your RowFilter , something like

dv.RowFilter = string.Format("Name LIKE '%{0}%' AND City LIKE '%{1}%'", txtSearchData.Text, txtSearchDataCity.Text)

You would have to iterate through the search terms that your user selects though so in the case of a listBox you could do something like this building up a string as you go

StringBuilder rowFilter = new StringBuilder();

foreach (var item in listBox1.SelectedItems)
{
    if(rowFilter.Length > 0)
    {
        rowFilter.Append(" or ");
        rowFilter.Append("Name LIKE '%" + item.ToString() "%'");
    }
}

Then for your RowFilter

dv.RowFilter = rowFilter;

This link may help as well - DataView RowFilter Syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM