Filtering DataSet Based On Column Values In C#

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:

table 

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:

  1. ds.Tables[0].DefaultView.RowFilter = "State = 'Maharashtra'";  
  2. DataTable dt = (ds.Tables[0].DefaultView).ToTable();  

Now, in DataTable dt, we will get the records from DataSet ds with State=Maharashtra.

table

We can also set this filtered DataSet directly as the DataSource of Gridview.

 

  1. ds.Tables[0].DefaultView.RowFilter = "State = 'Karnataka'";  
  2. GridView1.DataSource = ds.Tables[0].DefaultView;  
  3. GridView1.DataBind();  
table

 

We can also give multiple conditions in filtering with “and” or “or” operators. 
  1. ds.Tables[0].DefaultView.RowFilter = "State = 'Maharashtra' and City='Nagpur'";  
  2. DataTable dt = (ds.Tables[0].DefaultView).ToTable();   
Hoping that this will be helpful for someone!
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now