11

I have a Datagridview and the Data Source is dtCustomer I just want to filter the content of grid view based on a search text. Itried the following code

DataTable dtSearch =  dtCustomer;
dtSearch.Select("cust_Name like '" + txtSearch.Text + "%'");
grvCustomer.DataSource = dtSearch;

But this is not working. If any body knows the solution please share.

8 Answers 8

14

Try this:

dtSearch.DefaultView.RowFilter = "cust_Name like '" + txtSearch.Text + "%'";  

And check whatever there is space to be removed by triming the text.

8

The return value for DataTable.Select is a DataRow[] array. It returns a list of matching DataRows. Your code does nothing with those rows at the moment.

You can setup a DataView with a filter and set the grid's DataSource to the DataView:

DataView dv = new DataView(dtSearch);
dv.RowFilter = "...";
grvCustomer.DataSource = dv;
3

You could try using a DataView (code not tested) -

DataView dv = new DataView(dtSearch);
dv.RowFilter = "cust_Name like '" + txtSearch.Text + "%'";
grvCustomer.DataSource = dv;
3

Or Try this;

dataGridView.Datasource = datatable.Select("....").CopyToDataTable()
2
dtCustomer.Rows.Cast<DataRow>().Select(dr => (string)dr["cust_Name"].Startswith("zzz")).ToList()
2

You can do something like this.

DataView dv1 = dtDefault.DefaultView; 
dv1.RowFilter = "CusGroupId=1 and CustomerCode LIKE '"+txtCustomer.Text +"%'";  
DataTable dt=dv1.ToTable();
1

DataTable.Select returns array of row, but you are binding entire data table not filtered rows. use this way or DataView

DataTable dtSearch =  dtCustomer;
var filter = dtSearch.Select("cust_Name like '" + txtSearch.Text + "%'");
grvCustomer.DataSource = filter.ToList();
0

I think this is what you're looking for?

//DataTable dtSearch =  dtCustomer;
//dtSearch.Select("cust_Name like '" + txtSearch.Text + "%'");


grvCustomer.DataSource = dtCustomer.Select("cust_Name like '" + txtSearch.Text + "%'");

And when you want to go back to the original data

grvCustomer.DataSource = dtCustomer;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.