Search Asp.Net Here

How to filter Data in DataSet using C#



How to filter Data in DataSet

DataView Class is used to filter and sorting of data in Data Set
Here I m giving an example of how we can filter and sort data in data set.

DataView: A DataView is used to create different views of the data stored in a DataSet of DataTable

I am using following sqlserver database table in my example. Create a table using this script


CREATE TABLE tbemp
(
    eno int NULL ,
    ename varchar (50) NULL,
    eadd varchar (50) NULL,
    esal int NULL
)
GO


Use Following code in your .aspx page

<asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />
        <br />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click"
            Text="Show All Data" />

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Filter By Salary" ToolTip="Salary &gt; 20000 and &lt; 50000" />


I have used following namespaces in my .cs (code) file

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;



Now write followin code in your.cs file

    private DataSet getdata()
    {
        SqlConnection con = new SqlConnection("server=tiger;database=database1;uid=sa");
        SqlDataAdapter adp = new SqlDataAdapter("Select eno,ename,eadd,esal from tbemp", con);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        return ds;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataSet ds = getdata();
        //Filtering Data (Showing record where salary is >20000 and <50000
        DataView dv = ds.Tables[0].DefaultView;
        //RowFilter is used to filter data in dataview
        dv.RowFilter = "esal>=20000 and esal<=50000";// 'and' operator can be used for multipal conditions
        //Sorting Record in Descending order
        dv.Sort = "esal desc";//Sort property is used to data in dataview
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        DataSet ds = getdata();
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }




Comments :

8 comments to “How to filter Data in DataSet using C#”
Unknown said...
on 

thanks, it has been helped me.

Anonymous said...
on 

very simple and effective ....

Anonymous said...
on 

nice point to point description. was looking for it for half n hour.........thanks buddy

L said...
on 

very straight forward..thanks man..

Abi said...
on 

Good

Anonymous said...
on 

thank you
www.admamr.ru/news

vamsirays said...
on 

very very good , it helps me alot, thank you very much

Anonymous said...
on 

GridView filtering

Post a Comment