Filtering Dataset in C#

  • by
Filtering Dataset in C# - Continent

Filtering Dataset in C# can serve many purposes. It helps in faster data rendering on the view of our UI and avoid hassles of going again to our database and making calls to database. In this post I will explain how to filter Dataset in C#. This can be used in both C# windows form application and in C# ASP.NET websites.

See also : How to fill Data in Dataset ASP.NET

Filtering Dataset in C# :

Below is my dataset where I have already filled data from my database.

Filtering Dataset in C#

Filtering Dataset in C# -Dataset

Below is my code to fill data in dataset.

Code :

 protected void BindGridview()
 {
 SqlConnection con = new SqlConnection("Data Source=Hitesh;Initial Catalog=SimpleAsp;User Id=sa;password=rbs;");
 con.Open();
 SqlCommand cmd = new SqlCommand("select * from tblCountry", con);
 SqlDataAdapter da = new SqlDataAdapter(cmd);
 DataSet ds = new DataSet();

 da.Fill(ds);

 con.Close();
 datagrid.DataSource = ds.Tables[0].DefaultView;
 datagrid.DataBind();

 }

Filter queries for filtering dataset in C# are similar to that of filtering data in SQL. Here, after filling our dataset we have to write the query using the default view option of dataset.

To filter data according to Continents in our dataset, we will use default view row query as below :

ds.Tables[0].DefaultView.RowFilter = "Continent = 'Asia' ";
Filtering Dataset in C# - Continent

Filtering Dataset in C# – Continent

And reference our dataset default view to our datagrid source.

da.Fill(ds);
 ds.Tables[0].DefaultView.RowFilter = "Continent = 'Asia' ";
 datagrid.DataSource = ds.Tables[0].DefaultView;
 datagrid.DataBind();

Similarly, If we want to filter countries, write :

da.Fill(ds);
 ds.Tables[0].DefaultView.RowFilter = "Country = 'India' ";
 datagrid.DataSource = ds.Tables[0].DefaultView;
 datagrid.DataBind();

And to use like queries, write :

da.Fill(ds);
 ds.Tables[0].DefaultView.RowFilter = "Country like 'A%'";

con.Close();
 datagrid.DataSource = ds.Tables[0].DefaultView;
 datagrid.DataBind();

Query to filter multiple columns :

To filter multiple columns use :

da.Fill(ds);
ds.Tables[0].DefaultView.RowFilter = "Country = 'India'  and Continent = 'Asia'";
datagrid.DataSource = ds.Tables[0].DefaultView;
datagrid.DataBind();

Stay Happy.

 


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.