Search code examples
c#asp.netdataview

DataView RowFillter like operator


i am facing small issue in dataview rowfilter. How to handle textbox empty value in dataview rowfilter.i am using OR operator in this filter. Please help Guide me in this issue.so far i using below code.

Column1 = string.IsNullOrEmpty(txtColumn1.Text) ? "" : "%" + txtColumn1.Text + "%";
Column2 = string.IsNullOrEmpty(txtColumn2.Text) ? "" : "%" + txtColumn2.Text + "%";
Column3 = string.IsNullOrEmpty(txtColumn3.Text) ? "" : "%" + txtColumn3.Text + "%";

dataView.RowFilter = @"Column1 like '" + Column1 + "'" + "OR Column2 like '" + Column2 + "'" + "OR Column3 like '" + Column3 + "'";

Solution

  • The below code snippet will help you to control filtering with empty values. Plase try and mark the answer if it useful

    StringBuilder filter = new StringBuilder();
    if (!(string.IsNullOrEmpty(textBox1.Text)))
        filter.Append("Column1 Like '%" + textBox1.Text + "%'");
    
    if (!(string.IsNullOrEmpty(textBox2.Text)))
    {
       if (filter.Length > 0) filter.Append(" OR ");
       filter.Append("Column2 Like '%" + textBox2.Text + "%'");
    }
    
    if (!(string.IsNullOrEmpty(textBox3.Text)))
    {
       if (filter.Length > 0) filter.Append(" OR ");
       filter.Append("Column3 Like '%" + textBox3.Text + "%'");
    }
    
    DataView dv = dt.DefaultView;
    dv.RowFilter = filter.ToString();