Efficient DataGridView Filtering with DataSet: A Direct DataTable Approach
Filtering a DataGridView linked to a DataTable within a DataSet presents a unique challenge. Unlike scenarios where the DataTable is directly bound or a BindingSource is used, simply altering the DataTable's RowFilter
property doesn't automatically refresh the DataGridView's display.
This limitation stems from how the DataGridView handles DataSets. When the DataSource
is a DataSet, the DataMember
property dictates which DataTable is shown. Modifying the RowFilter
of a DataTable not specified by DataMember
has no visible effect on the grid.
The solution involves directly accessing and manipulating the correct DataTable:
<code class="language-csharp">private void textBox1_TextChanged(object sender, EventArgs e) { DataSet ds = (DataSet)dataGridView1.DataSource; DataTable dt = ds.Tables[dataGridView1.DataMember]; dt.DefaultView.RowFilter = string.Format("country LIKE '%{0}%'", textBox1.Text); }</code>
This code snippet retrieves the active DataTable using the DataGridView's DataMember
property and then applies the filter to its DefaultView
. This directly updates the DataGridView's display without requiring a change to the DataSource
property.
Crucially, this method avoids exceptions that might arise from attempting to recast the DataSource
back to a DataSet, ensuring compatibility with existing code.
The above is the detailed content of How to Filter a DataGridView Bound to a DataSet without Changing its DataSource?. For more information, please follow other related articles on the PHP Chinese website!