ASP.Net GridView sorting and filtering using header in C#

indradeo
 
on Oct 16, 2021 01:25 AM
Sample_193886.zip
653 Views

Dear Sir ,

need your help here, i want to sort gridview using header.

how to do this.

namespace TS
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                BindGridView();
            }
            if (Session["FirstName"] == null)
                Response.Redirect("Index.aspx");
            else
            {
                String EmplooyeId = Convert.ToString((int)Session["empid"]);
                Label2.Text = "" + EmplooyeId + "";
                String FirstName = Session["FirstName"].ToString();
                String LastName = Session["LastName"].ToString();
                String Department = Session["Department"].ToString();
                lbluserInfo.Text = "Department: " + Department + ".";
                Label1.Text = "Welcome " + FirstName + " " + LastName + ".";
            }
        }

        private void BindGridView()
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            SqlConnection con = new SqlConnection(constr);
            // SqlCommand cmd = new SqlCommand("select * from ts3 where [empid]= '" +Session["empid"].ToString()+"' ORDER BY Id DESC", con);
            SqlCommand cmd = new SqlCommand("select * from ts4 ORDER BY Id asc", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            con.Close();
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditButton")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = GridView1.Rows[index];
               // Response.Redirect("Edit1.aspx?Id=" + row.Cells[0].Text);
                //Response.Redirect("Edit1.aspx?Name=" + Label2.Text +"");

                Response.Redirect("Edit1.aspx?Id=" + row.Cells[0].Text + "&empid=" + Label2.Text);
            }               
        }
       
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            
        }

        protected void Save(object sender, EventArgs e)
        {
            Response.Redirect("Default1.aspx?empid=" + Label2.Text + "");
        }
    }
}

 

 

<asp:GridView ID="GridView1" HeaderStyle-BackColor="#99ccff"
    HeaderStyle-ForeColor="black" runat="server" Font-Size="15pt" AutoGenerateColumns="false"
    HeaderStyle-Font-Size="16pt" OnRowCommand="GridView1_RowCommand"
    EmptyDataText="There Is No Records In Database!" Height="240px" Width="1209px"
    CssClass="auto-style7">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="SL.No" Visible="true" />
        <asp:BoundField DataField="empid" HeaderText="Empid" Visible="true" />
        <asp:BoundField DataField="section" HeaderText="Section" DataFormatString="{0:dd-MM-yyy}" ItemStyle-Width="100px" />
        <asp:BoundField DataField="wrk_nm" HeaderText="Work Name " />
        <asp:BoundField DataField="fts_no" HeaderText="FTS No." />
        <asp:BoundField DataField="processed_by_section_on" HeaderText="Processed by Section on" />
        <asp:BoundField DataField="received_in_cnm" HeaderText="Received in C&M" />
        <asp:BoundField DataField="estmt_cst_wtout_gst" HeaderText="Estimate Cost without GST" />    
        <asp:BoundField DataField="current_status" HeaderText="Current status" />
        <asp:BoundField DataField="actn_rqrd" HeaderText="Action Required" />
        <asp:BoundField DataField="rspncblty" HeaderText="Rspsblty" />
        <asp:BoundField DataField="lst_updated_by" HeaderText="Last Updated By" />
        <asp:BoundField DataField="rmk" HeaderText="Priority " />
        <asp:TemplateField HeaderText="Update">  
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" Text="Edit" runat="server" OnClick="LinkButton1_Click" CommandName="EditButton" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
            </ItemTemplate>
        </asp:TemplateField>                                  
    </Columns>                                  
</asp:GridView>
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 18, 2021 05:05 AM

Hi indradeo,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="There Is No Records In Database!"
    AllowPaging="true" PageSize="10" OnPageIndexChanging="OnPaging" AllowSorting="true" OnSorting="GridView1_Sorting">
    <Columns>
        <asp:BoundField DataField="CustomerID" SortExpression="CustomerID" HeaderText="CustomerID" />
        <asp:BoundField DataField="ContactName" SortExpression="ContactName" HeaderText="ContactName" />
        <asp:TemplateField>
            <HeaderTemplate>
                Section
                <asp:DropDownList ID="section" runat="server" SortExpression="section"
                    AutoPostBack="true" OnSelectedIndexChanged="DeptChanged"
                    AppendDataBoundItems="true">
                    <asp:ListItem Text="ALL" Value="ALL"></asp:ListItem>
                    <asp:ListItem Text="Top 10" Value="10"></asp:ListItem>
                </asp:DropDownList>
            </HeaderTemplate>
            <ItemTemplate>
                <%# Eval("Country") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespaces

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

Code

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ViewState["Filter"] = "ALL";
        DataTable dt = BindGridView();
        TableCell tableCell = GridView1.HeaderRow.Cells[0];
        Image img = new Image();
        img.ImageUrl = "~/Images/asc.png";
        tableCell.Controls.Add(new LiteralControl("&nbsp;"));
        tableCell.Controls.Add(img);
        ViewState["tables"] = dt;
    }
}

private DataTable BindGridView()
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM Customers";
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            if (ViewState["Filter"].ToString() == "ALL")
            {

            }
            else if (ViewState["Filter"].ToString() == "10")
            {
                query = "SELECT TOP 10 * FROM Customers";
            }
            else
            {
                query += " WHERE Country = @Filter";
                cmd.Parameters.AddWithValue("@Filter", ViewState["Filter"].ToString());
            }

            cmd.CommandText = query;
            cmd.Connection = con;
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }

    DropDownList section = (DropDownList)GridView1.HeaderRow.FindControl("section");
    this.BindCountryList(section);

    return dt;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    string SortDir = string.Empty;
    DataTable dt = new DataTable();
    dt = ViewState["tables"] as DataTable;
    if (dir == SortDirection.Ascending)
    {
        dir = SortDirection.Descending;
        SortDir = "Desc";
    }
    else
    {
        dir = SortDirection.Ascending;
        SortDir = "Asc";
    }
    DataView sortedView = new DataView(dt);
    sortedView.Sort = e.SortExpression + " " + SortDir;
    GridView1.DataSource = sortedView;
    GridView1.DataBind();
    DropDownList section = (DropDownList)GridView1.HeaderRow.FindControl("section");
    this.BindCountryList(section);
    for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        if (GridView1.HeaderRow.Cells[i].Controls[0].GetType().Name == "DataControlLinkButton")
        {
            string lbText = ((LinkButton)GridView1.HeaderRow.Cells[i].Controls[0]).Text;
            if (lbText == e.SortExpression)
            {
                TableCell tableCell = GridView1.HeaderRow.Cells[i];
                Image img = new Image();
                img.ImageUrl = (SortDir == "Asc") ? "~/Images/asc.png" : "~/Images/desc.png";
                tableCell.Controls.Add(new LiteralControl("&nbsp;"));
                tableCell.Controls.Add(img);
            }
        }
    }
}

public SortDirection dir
{
    get
    {
        if (ViewState["dirState"] == null)
        {
            ViewState["dirState"] = SortDirection.Ascending;
        }
        return (SortDirection)ViewState["dirState"];
    }
    set
    {
        ViewState["dirState"] = value;
    }
}

protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    BindGridView();
    TableCell tableCell = GridView1.HeaderRow.Cells[0];
    Image img = new Image();
    img.ImageUrl = "~/Images/asc.png";
    tableCell.Controls.Add(new LiteralControl("&nbsp;"));
    tableCell.Controls.Add(img);
}

protected void DeptChanged(object sender, EventArgs e)
{
    DropDownList ddlCountry = (DropDownList)sender;
    ViewState["Filter"] = ddlCountry.SelectedValue;
    this.BindGridView();
    TableCell tableCell = GridView1.HeaderRow.Cells[0];
    Image img = new Image();
    img.ImageUrl = "~/Images/asc.png";
    tableCell.Controls.Add(new LiteralControl("&nbsp;"));
    tableCell.Controls.Add(img);
}

private void BindCountryList(DropDownList Dept)
{
    String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("SELECT DISTINCT Country FROM Customers");
    cmd.Connection = con;
    con.Open();
    Dept.DataSource = cmd.ExecuteReader();
    Dept.DataTextField = "Country";
    Dept.DataValueField = "Country";
    Dept.DataBind();
    con.Close();
    Dept.Items.FindByValue(ViewState["Filter"].ToString()).Selected = true;
}