In this blog, we will learn, how to filter a DataSet, based on the value of a particular column. Suppose, we have a DataSet ‘ds’ with the records of some users, given below:
Now, we want to filter this DataSet, based on States.
For example, we have to get the records with State as “Maharashtra” only
Afterwards, we can write the code, given below:
- ds.Tables[0].DefaultView.RowFilter = "State = 'Maharashtra'";
- DataTable dt = (ds.Tables[0].DefaultView).ToTable();
Now, in DataTable dt, we will get the records from DataSet ds with State=Maharashtra.
We can also set this filtered DataSet directly as the DataSource of Gridview.
- ds.Tables[0].DefaultView.RowFilter = "State = 'Karnataka'";
- GridView1.DataSource = ds.Tables[0].DefaultView;
- GridView1.DataBind();
We can also give multiple conditions in filtering with “and” or “or” operators.
- ds.Tables[0].DefaultView.RowFilter = "State = 'Maharashtra' and City='Nagpur'";
- DataTable dt = (ds.Tables[0].DefaultView).ToTable();
Hoping that this will be helpful for someone!