Dot Net For All

C# Tip: Adding multiple conditions for DataTable RowFilter

Hello Friends, We can put a filter on the DataTable in C# or VB.NET and use some condition to filter out the data. We often use DefaultView which works on the top of the DataTable. It basically creates a temporary view for the DataTable.

Multiple Condition RowFilter

Suppose we have binded our DataTable and we want to filter the data based on the text entered in the TextBox.

Row filter works on the DataTable and it doesn’t execute the query on the underlying database.

dtStudents.DefaultView.RowFilter = "firstName like '%" + strFilter + "%' or lastName like '%" + strFilter + "'% ";

In the above code example the strFilter is the text entered in the search TextBox.

But now suppose if we have more drop down that has all the standards and once the standard is selected, the filter should also keep that in consideration.

         If (cboStandard.SelectedIndex > 0)
        {
            strIkType = "iStandard = " + cboStandard.SelectedValue.ToString + "";
        }
      
        If (String.IsNullOrEmpty(strIkType)) 
        {
               dtStudents.DefaultView.RowFilter = "firstName like '%" + strFilter + "%' or lastName like '%" + strFilter + "'% ";
        }
        else{
                dtStudents.DefaultView.RowFilter = "firstName like '%" + strFilter + "%' or lastName like '%" + strFilter + "'%) AND " & strIkType & "";
        }
        

In the above code example I have created a dynamic query based on the item selected on the drop down.

Finally we can bind the DataTable to the grid we want to show in the UI.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview