I\'m developing user control in C# Visual Studio 2010 - a kind of \"quick find\" textbox for filtering datagridview. It should work for 3 types of datagridview datasources:
I have a clearer proposal on automatic search in a DataGridView
this is an example
private void searchTb_TextChanged(object sender, EventArgs e)
{
try
{
(lecteurdgview.DataSource as DataTable).DefaultView.RowFilter = String.IsNullOrEmpty(searchTb.Text) ?
"lename IS NOT NULL" :
String.Format("lename LIKE '{0}' OR lecni LIKE '{1}' OR ledatenais LIKE '{2}' OR lelieu LIKE '{3}'", searchTb.Text, searchTb.Text, searchTb.Text, searchTb.Text);
}
catch (Exception ex) {
MessageBox.Show(ex.StackTrace);
}
}
I just spent an hour on a similar problem. For me the answer turned out to be embarrassingly simple.
(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
You could create a DataView object from your datasource. This would allow you to filter and sort your data without directly modifying the datasource.
Also, remember to call dataGridView1.DataBind();
after you set the data source.
I found a simple way to fix that problem. At binding datagridview you've just done: datagridview.DataSource = dataSetName.Tables["TableName"];
If you code like:
datagridview.DataSource = dataSetName;
datagridview.DataMember = "TableName";
the datagridview will never load data again when filtering.
I developed a generic statement to apply the filter:
string rowFilter = string.Format("[{0}] = '{1}'", columnName, filterValue);
(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = rowFilter;
The square brackets allow for spaces in the column name.
Additionally, if you want to include multiple values in your filter, you can add the following line for each additional value:
rowFilter += string.Format(" OR [{0}] = '{1}'", columnName, additionalFilterValue);
//"Comment" Filter datagrid without changing dataset,Perfectly works.
(dg.ItemsSource as ListCollectionView).Filter = (d) =>
{
DataRow myRow = ((System.Data.DataRowView)(d)).Row;
if (myRow["FName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()) || myRow["LName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()))
return true; //if want to show in grid
return false; //if don't want to show in grid
};