DataGridView Row Filter Where condition is = [SomeString] ~Anything~ [SomeString]

1.4k views Asked by At

I have rowfilter from textbox input and here is how it looks like

var dt = (DataTable)dataGridView1.DataSource;
            try
            {
                dt.DefaultView.RowFilter = string.Format("KATBR like '%{0}%'", filterKatbr.Text.Trim().Replace("'", "''")) + "AND " + string.Format("NAZIV like '%{0}%'", filterNaziv.Text.Trim().Replace("'", "''"));
                dataGridView1.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

It supports 2 textbox and filter from 2 textbox in same time but for now lets focus on one textbox. What i want to achieve is if i type in textbox something like this Computer%Land, it needs to filter me everything that must have Computer then any characterS between and then must have Land after it.

It doesn't matter what character is used for that anything between. I used % but it can be anything.

So if i had table like this:

|Computer432Land     |
|Computer321 Land    |
|Land 213 Computer   |
|Computer asd13  Land|

Result would be first, second and fourth column.

2

There are 2 answers

1
OhBeWise On

Don't think of your filter as a single statement, but instead as two statements to be joined. That is, you need everything that:

  1. Starts with "Computer"; and
  2. Ends with "Land"

Like so:

dt.DefaultView.RowFilter = "ColumnName like 'Computer%' AND ColumnName like '%Land'";

As shown below, using your example data++ we see the expected results.

DataTable dt = new DataTable();

dt.Columns.Add("ColumnName", typeof(string));

dt.Rows.Add("Computer432Land");
dt.Rows.Add("Computer31 Land");
dt.Rows.Add("Land 213 Computer");
dt.Rows.Add("Computer asd13 Land");
dt.Rows.Add("Computer asd13");
dt.Rows.Add("asd13 Land");

dataGridView1.DataSource = dt;

DataGridView screenshot only displaying rows containing the data "Computer432Land", "Computer31 Land", and "Computer asd13 Land"

0
Parpil On

Oh it was catchy because of splitting string but here is how i made it (it is working only with one '%')

string filterNazivStr = filterNaziv.Text;
if(filterNazivStr.ToLower().Contains('%'))
{
    int i= 0;
    string first = "";
    string second = "";
    Char separator = '%';
    String[] substrings = filterNazivStr.Split(separator);
    foreach (var substring in substrings)
        {
            switch (i)
            {
                case 0:
                    first = substring;
                        break;
                case 1:
                    second = substring;
                        break;
                default:
                    break;
            }
            i++;
        }
        dt.DefaultView.RowFilter = string.Format("NAZIV like '%{0}%'", first) + " AND " + string.Format("NAZIV like '%{0}%'", second);
    }