Using the C1FlexGrid Control > C1FlexGrid Filtering > Applying filters programmatically |
Filters are applied when the user edits them, and also when they are applied to a column. They are not automatically applied when the data changes. To apply the filters to the data currently loaded on the grid, call the grid's ApplyFilters method.
For example, the code below enables an ApplyFilter button when the user edits the data on the grid. Clicking the ApplyFilter button applies the filter and disables the button until the next change.
To write code in C#
C# |
Copy Code
|
---|---|
public Form1() { InitializeComponent(); // get some data var da = new OleDbDataAdapter("select * from products", GetConnectionString()); var dtProducts = new DataTable(); da.Fill(dtProducts); // bind the grid to the data _flex.DataSource = dtProducts; // enable filtering _flex.AllowFiltering = true; // monitor changes to enable ApplyFilter button _flex.AfterEdit += _flex_AfterEdit; } |
The code above binds the grid to a data source, enables filtering by setting the AllowFiltering property to True, and connects an event handler to the AfterEdit event. The event handler implementation follows:
To write code in C#
C# |
Copy Code
|
---|---|
void _flex_AfterEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) { foreach (C1.Win.C1FlexGrid.Column c in _flex.Cols) { if (c.ActiveFilter != null) { _btnApplyFilters.Enabled = true; break; } } } |
This code scans all columns to determine whether a filter is defined for any column. If an active filter is detected, the code enables the button that applies the filter to the current data. When the button is clicked, the following event handler executes:
To write code in C#
C# |
Copy Code
|
---|---|
private void _btnApplyFilters_Click(object sender, EventArgs e) { _flex.ApplyFilters(); _btnApplyFilters.Enabled = false; } |
The code simply applies all the active filters and disables the button until the next change.
If instead of requiring a button click you simply wanted to apply the filter after every edit, you could call the ApplyFilter directly from the AfterEdit event handler, as shown below:
To write code in C#
C# |
Copy Code
|
---|---|
void _flex_AfterEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e) { _flex.ApplyFilters(); } |