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.
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' ";
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.