Jul 13, 2012

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();
    }

No comments:

Post a Comment