Articles in this section
Category / Section

How to add filter in WinForms GridControl?

4 mins read

There is no built-in support for having a filter bar in a GridControl, because the GridFilterBar uses DataView’s RowFilter property for filtering.

If you are using the GridControl in virtual mode with a data table then the filter bar function can be implemented. In the given sample, the GridControlFilterBar is created to enable filter bar in grid control.

Creating the GridControlFilterBar:

C#

public class GridControlFilterBar
{
    private GridControl _grid;
    private DataView filterView;
    private DataView originalView;
    public int RowCount;
    public int FilterRowIndex = 1;
   
   //Wire the Grid with the filterbar
   public void WireGrid(GridControl grid, DataTable dt)
   {
 this._grid = grid;
 this.originalView = dt.DefaultView;
 this.filterView = new DataView(dt);
 RowCount = dt.Rows.Count + 1;
 _grid.Model.Rows.FrozenCount += 1;
 if(this._grid != null)
 {
  this._grid.CurrentCellAcceptedChanges += new CancelEventHandler(_grid_CurrentCellAcceptedChanges);
  this._grid.CurrentCellCloseDropDown += new Syncfusion.Windows.Forms.PopupClosedEventHandler(_grid_CurrentCellCloseDropDown);
  this._grid.QueryCellInfo += new GridQueryCellInfoEventHandler(_grid_QueryCellInfo);
  _grid.Refresh();
 }
   }
 
   bool inUnwire = false;
 
    //Unwire the Grid from the filter 
    public void UnwireGrid()
    {
 this._grid.CurrentCellAcceptedChanges -= new CancelEventHandler(_grid_CurrentCellAcceptedChanges);
 this._grid.CurrentCellCloseDropDown -= new Syncfusion.Windows.Forms.PopupClosedEventHandler(_grid_CurrentCellCloseDropDown);
 this._grid.QueryCellInfo -= new GridQueryCellInfoEventHandler(_grid_QueryCellInfo);
 originalView.RowFilter = "";
 this.RowCount = originalView.Table.Rows.Count;
 _grid.Model.Rows.FrozenCount -= 1;
 inUnwire = true;
 for(int i = 1;i<_grid.ColCount;i++)
  _grid[FilterRowIndex,i].Text ="";
 _grid.Refresh();
 this._grid = null;
 inUnwire = false;
    }
 
    //Return the Grid is wired or not.
    public bool IsWired
    {
 get{return (this._grid!= null)&&!inUnwire;}
    }
 
    //Data table for creating a unique entries 
    protected virtual DataTable CreateUniqueEntries(string colName)
    {
 DataRow row1;
 DataTable table1 = new DataTable(colName);
 table1.Columns.Add(new DataColumn(colName));
 row1 = table1.NewRow();
 row1[0] = "[None]";
 table1.Rows.Add(row1);
 string text1 = "";
 ArrayList tempArray = new ArrayList();
 filterView.Sort = colName +" ASC";
 for (int num1 = 0; num1 < filterView.Count; num1++)
 {
  text1 = filterView[num1].Row[colName].ToString();
  if(tempArray.Count==0 || !tempArray.Contains(text1))
  {
   row1 = table1.NewRow();
   row1[0] = text1;
   tempArray.Add(text1);
   table1.Rows.Add(row1);
  }
 }
 return table1;
    }
 
    //Filter collection
    ArrayList filters = new ArrayList();
 
    struct filter
    {
 public string colname,filterString;
 public filter(string colname, string filterString)
 {
  this.colname = colname;
  this.filterString = filterString;
 }
    }
 
    //Setting the filter condition 
    public void SetFilters()
    {
 string FilterString = "";
 foreach(filter fil in filters)
 {
  if(filters.IndexOf(fil)>0)
   FilterString += " AND ";
 
  FilterString += "["+fil.colname+"] = "+fil.filterString;
 }
 originalView.RowFilter = FilterString;
 RowCount = originalView.Count+1;
 _grid.Refresh();
    }
}

VB

Public Class GridControlFilterBar
 Private _grid As GridControl
 Private filterView As DataView
 Private originalView As DataView
 Public RowCount As Integer
 Public FilterRowIndex As Integer = 1
 
   'Wire the Grid with the filterbar
   Public Sub WireGrid(ByVal grid As GridControl, ByVal dt As DataTable)
 Me._grid = grid
 Me.originalView = dt.DefaultView
 Me.filterView = New DataView(dt)
 RowCount = dt.Rows.Count + 1
 _grid.Model.Rows.FrozenCount += 1
 If Me._grid IsNot Nothing Then
  AddHandler _grid.CurrentCellAcceptedChanges, AddressOf _grid_CurrentCellAcceptedChanges
  AddHandler _grid.CurrentCellCloseDropDown, AddressOf _grid_CurrentCellCloseDropDown
  AddHandler _grid.QueryCellInfo, AddressOf _grid_QueryCellInfo
  _grid.Refresh()
 End If
   End Sub
 
   Private inUnwire As Boolean = False
 
 'Unwire the Grid from the filter 
 Public Sub UnwireGrid()
 RemoveHandler _grid.CurrentCellAcceptedChanges, AddressOf _grid_CurrentCellAcceptedChanges
 RemoveHandler _grid.CurrentCellCloseDropDown, AddressOf _grid_CurrentCellCloseDropDown
 RemoveHandler _grid.QueryCellInfo, AddressOf _grid_QueryCellInfo
 originalView.RowFilter = ""
 Me.RowCount = originalView.Table.Rows.Count
 _grid.Model.Rows.FrozenCount -= 1
 inUnwire = True
 For i As Integer = 1 To _grid.ColCount - 1
  _grid(FilterRowIndex,i).Text =""
 Next i
 _grid.Refresh()
 Me._grid = Nothing
 inUnwire = False
 End Sub
 
 'Return the Grid is wired or not.
 Public ReadOnly Property IsWired() As Boolean
 Get
  Return (Me._grid IsNot Nothing) AndAlso Not inUnwire
 End Get
 End Property
 
 'Data table for creating a unique entries 
 Protected Overridable Function CreateUniqueEntries(ByVal colName As String) As DataTable
           Dim row1 As DataRow
           Dim table1 As New DataTable(colName)
           table1.Columns.Add(New DataColumn(colName))
           row1 = table1.NewRow()
           row1(0) = "[None]"
           table1.Rows.Add(row1)
           Dim text1 As String = ""
           Dim tempArray As New ArrayList()
           filterView.Sort = colName &" ASC"
           For num1 As Integer = 0 To filterView.Count - 1
               text1 = filterView(num1).Row(colName).ToString()
               If tempArray.Count=0 OrElse (Not tempArray.Contains(text1)) Then
                  row1 = table1.NewRow()
                  row1(0) = text1
                  tempArray.Add(text1)
                  table1.Rows.Add(row1)
               End If
           Next num1
           Return table1
 End Function
 
 'Filter collection
 Private filters As New ArrayList()
 
 Private Structure filter
 Public colname, filterString As String
 Public Sub New(ByVal colname As String, ByVal filterString As String)
  Me.colname = colname
  Me.filterString = filterString
 End Sub
 End Structure
 
 'Setting the filter condition 
 Public Sub SetFilters()
 Dim FilterString As String = ""
 For Each fil As filter In filters
  If filters.IndexOf(fil)>0 Then
   FilterString &= " AND "
  End If
 
  FilterString &= "[" & fil.colname &"] = " & fil.filterString
 Next fil
 originalView.RowFilter = FilterString
 RowCount = originalView.Count+1
 _grid.Refresh()
 End Sub
End Class
 

Event Handlers for the GridControlFilterBar:

C#

private void _grid_CurrentCellAcceptedChanges(object sender, CancelEventArgs e)
{
    GridCurrentCell cc = this._grid.CurrentCell;
    if(cc.ColIndex>0 && cc.RowIndex ==1)
    {
        foreach(filter fil in filters)
        {
   if(fil.colname == originalView.Table.Columns[cc.ColIndex - 1].ColumnName)
   {
       filters.Remove(fil);
       break;
   }
        }
        if(cc.Renderer.StyleInfo.Text != "[None]")
   filters.Add(new filter(originalView.Table.Columns[cc.ColIndex - 1].ColumnName,"'" + cc.Renderer.StyleInfo.Text + "'"));
   SetFilters();
    }
}
private void _grid_CurrentCellCloseDropDown(object sender, Syncfusion.Windows.Forms.PopupClosedEventArgs e)
{
    GridCurrentCell cc = this._grid.CurrentCell;
    if(cc.ColIndex>0 && cc.RowIndex ==1)
        cc.ConfirmChanges();
}
private void _grid_QueryCellInfo(object sender, GridQueryCellInfoEventArgs e)
{
    if(e.ColIndex>0 && e.RowIndex == FilterRowIndex)
    {
        e.Style.CellType = GridCellTypeName.ComboBox;
        e.Style.ExclusiveChoiceList = true;
        e.Style.DataSource = CreateUniqueEntries(originalView.Table.Columns[e.ColIndex - 1].ColumnName);
        e.Style.ValueMember = originalView.Table.Columns[e.ColIndex - 1].ColumnName;
    }
}

VB

Private Sub _grid_CurrentCellAcceptedChanges(ByVal sender As Object, ByVal e As CancelEventArgs)
     Dim cc As GridCurrentCell = Me._grid.CurrentCell
     If cc.ColIndex>0 AndAlso cc.RowIndex =1 Then
         For Each fil As filter In filters
    If fil.colname = originalView.Table.Columns(cc.ColIndex - 1).ColumnName Then
                 filters.Remove(fil)
     Exit For
     End If
 Next fil
 If cc.Renderer.StyleInfo.Text <> "[None]" Then
     filters.Add(New filter(originalView.Table.Columns(cc.ColIndex - 1).ColumnName,"'" & cc.Renderer.StyleInfo.Text & "'"))
 End If
 SetFilters()
     End If
End Sub
Private Sub _grid_CurrentCellCloseDropDown(ByVal sender As Object, ByVal e As Syncfusion.Windows.Forms.PopupClosedEventArgs)
    Dim cc As GridCurrentCell = Me._grid.CurrentCell
    If cc.ColIndex>0 AndAlso cc.RowIndex =1 Then
       cc.ConfirmChanges()
    End If
End Sub
Private Sub _grid_QueryCellInfo(ByVal sender As Object, ByVal e As GridQueryCellInfoEventArgs)
    If e.ColIndex>0 AndAlso e.RowIndex = FilterRowIndex Then
       e.Style.CellType = GridCellTypeName.ComboBox
       e.Style.ExclusiveChoiceList = True
       e.Style.DataSource = CreateUniqueEntries(originalView.Table.Columns(e.ColIndex - 1).ColumnName)
       e.Style.ValueMember = originalView.Table.Columns(e.ColIndex - 1).ColumnName
    End If
End Sub

Wiring the Grid with the GridControlFilterBar:

C#

GridControlFilterBar filterBar;
private void Form1_Load(object sender, System.EventArgs e)
{
    //Creating the object for GridControlFilterBar 
    filterBar = new GridControlFilterBar();
    filterBar.WireGrid(this.gridControl1,this.dt);
 
    //Hook the event to wire/unwire the grid from filter
    this.btnWire.Click += btnWire_Click;   
}
void btnWire_Click(object sender, EventArgs e)
{
    //Wire/unwire the Grid from the filter bar
    if (this.filterBar.IsWired)
        this.filterBar.UnwireGrid();
    else
        this.filterBar.WireGrid(this.gridControl1, this.dt);
}

VB

Private filterBar As GridControlFilterBar
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
 'Creating the object for GridControlFilterBar 
 filterBar = New GridControlFilterBar()
 filterBar.WireGrid(Me.gridControl1,Me.dt)
 
 'Hook the event to wire/unwire the grid from filter
 AddHandler Me.btnWire.Click, AddressOf btnWire_Click
End Sub
Private Sub btnWire_Click(ByVal sender As Object, ByVal e As EventArgs)
 'Wire/unwire the Grid from the filter bar
 If Me.filterBar.IsWired Then
  Me.filterBar.UnwireGrid()
 Else
  Me.filterBar.WireGrid(Me.gridControl1, Me.dt)
 End If
End Sub

View sample in GitHub

Enable the filter in GridControl

Conclusion

I hope you enjoyed learning about how to add filter in WinForms GridControl.

You can refer to our WinForms GridControl feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our WinForms GridControl example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied