Code for Export data to excel, Sorting, Filtering and Paging GridView data in Aps.Net- c#

  • Place the whole code in .aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NewGridTest.aspx.cs" Inherits="NewGridTest"  EnableEventValidation="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
        <div>
            <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False"
                Font-Names="Verdana" AllowPaging="True" AlternatingRowStyle-BackColor="#EFF3FB" AllowSorting="True" PageSize="5" Width="40%"
                OnPageIndexChanging="PageIndexChanging" BorderColor="#CCCCCC" BorderStyle="Solid"
                BorderWidth="1px" OnSorting="Sorting">
                <PagerStyle BorderColor="#FFFFFF" BorderStyle="Solid" BorderWidth="1px" />
                <HeaderStyle Height="30px" ForeColor="White" BackColor="#507CD1" Font-Size="12px" BorderColor="#FFFFFF"
                    BorderStyle="Solid" BorderWidth="1px" />
                <RowStyle Height="20px" Font-Size="11px" BorderColor="#CCCCCC" BorderStyle="Solid"
                    BorderWidth="1px" />
                <Columns>
                    <asp:BoundField DataField="UserId" HeaderText="UserId" SortExpression="UserId" />
                    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                    <asp:BoundField DataField="Designation" HeaderText="Designation" SortExpression="Designation" />
                    <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />
                </Columns>
            </asp:GridView>
             <br /><br />
  
    <asp:DropDownList ID="ddlDesignation" runat="server" AutoPostBack="True"
        onselectedindexchanged="ddlDesignation_SelectedIndexChanged">
         <asp:ListItem></asp:ListItem>
        <asp:ListItem>CRM</asp:ListItem>
        <asp:ListItem>Navision</asp:ListItem>
    </asp:DropDownList>
    <asp:DropDownList ID="ddlDepartment" runat="server" AutoPostBack="True"
        onselectedindexchanged="ddlDepartment_SelectedIndexChanged">
        <asp:ListItem></asp:ListItem>
        <asp:ListItem>Tech Lead</asp:ListItem>
        <asp:ListItem>Associate Technical Consultant</asp:ListItem>
    </asp:DropDownList>
           <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Filter.jpg"
        Height="22px" Width="22px" onclick="ImageButton1_Click" />
    <asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
    <asp:Label ID="Label2" runat="server" Text="Label" Visible="False"></asp:Label>
   
      <br /><br />
        <asp:Button ID="btnExcel" runat="server" Text="Export To Excel"
        onclick="btnExcel_Click" />
        </div>
       
    </div>
    </form>
</body>
</html>



  • Now place below codes in your .aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;
using System.Drawing;


public partial class NewGridTest : System.Web.UI.Page
{
    string Sort_Direction = "UserId ASC";
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["SortExpr"] = Sort_Direction;
            DataView dv = getData("");
            gvDetails.DataSource = dv;
            gvDetails.DataBind();
        }
    }


    protected void BindGrid(string filter)
    {
        gvDetails.DataSource = this.getData(filter);
        gvDetails.DataBind();
    }

    private DataView getData(string filter)
    {
        DataSet dsEmployee = new DataSet();

        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Designation", typeof(string));
        dt.Columns.Add("Department", typeof(string));

        DataRow dr = dt.NewRow();
        dr["UserId"] = 101;
        dr["Name"] = "Zaheer";
        dr["Designation"] = "Associate Technical Consultant";
        dr["Department"] = null;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 12;
        dr["Name"] = "Anish";
        dr["Designation"] = "CRM";
        dr["Department"] = "Associate Technical Consultant";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 113;
        dr["Name"] = "Manish";
        dr["Designation"] = "Tech Lead";
        dr["Department"] = "Navision";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 4;
        dr["Name"] = "Ravish";
        dr["Designation"] = "Tech Lead";
        dr["Department"] = "CRM";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 19;
        dr["Name"] = "Rajnsh";
        dr["Designation"] = "Tech Lead";
        dr["Department"] = "CRM";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 103;
        dr["Name"] = "Santosh";
        dr["Designation"] = null;
        dr["Department"] = "Navision";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 44;
        dr["Name"] = "Rakesh";
        dr["Designation"] = "Tech Lead";
        dr["Department"] = "Navision";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 22;
        dr["Name"] = "Vinay";
        dr["Designation"] = "Associate Technical Consultant";
        dr["Department"] = "Navision";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 73;
        dr["Name"] = "Manish";
        dr["Designation"] = "Tech Lead";
        dr["Department"] = "CRM";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 27;
        dr["Name"] = "Arnav";
        dr["Designation"] = "Associate Technical Consultant";
        dr["Department"] = "CRM";
        dt.Rows.Add(dr);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
                {
                    dt.Rows[i][j] = "Data Not Available";
                }
            }
        }

        DataView dv = new DataView(dt);
        dv.Sort = ViewState["SortExpr"].ToString();
        if (filter != string.Empty)
            dv.RowFilter = filter;
        return dv;
    }

    protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvDetails.PageIndex = e.NewPageIndex;
        DataView dv = getData("");
        gvDetails.DataSource = dv;
        gvDetails.DataBind();
    }

    protected void Sorting(object sender, GridViewSortEventArgs e)
    {
        string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
        if (SortOrder[0] == e.SortExpression)
        {
            if (SortOrder[1] == "ASC")
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
            }
        }
        else
        {
            ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
        }
        gvDetails.DataSource = getData("");
        gvDetails.DataBind();
    }

    protected void btnExcel_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        // gvDetails.AllowPaging = true;

        int j = 1;
        //This loop is used to apply stlye to cells based on particular row
        foreach (GridViewRow gvrow in gvDetails.Rows)
        {
            gvrow.BackColor = Color.White;
            if (j <= gvDetails.Rows.Count)
            {
                if (j % 2 != 0)
                {
                    for (int k = 0; k < gvrow.Cells.Count; k++)
                    {
                        gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                    }
                }
            }
            j++;
        }
        gvDetails.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        if (Label1.Text.Length <= 0)
        {
            sb.Append("");
        }
        if (Label2.Text.Length <= 0)
        {
            sb.Append("");
        }
        if (Label1.Text.Length > 0)
        {
            sb.Append("Department like '%" + Label1.Text + "%'");
        }
        if (Label2.Text.Length > 0)
        {
            if (sb.Length > 0)
            {
                sb.Append(" and ");
            }
            sb.Append("Designation like '%" + Label2.Text + "%'");
        }
        BindGrid(sb.ToString());
    }

    protected void ddlDesignation_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Text = ddlDesignation.SelectedItem.ToString();
    }
    protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label2.Text = ddlDepartment.SelectedItem.ToString();
    }
}

Comments

Popular posts from this blog

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

go to top image