Search...

Thursday, February 16, 2012

Gridview sorting and paging in Asp.Net



*********************************************************************************


/*Add Stylesheet in your application names StyleSheet.css*/

body {}
.gridView{width:100%;background:#ffffff;border:1px solid #476db6; border-collapse:separate;}
.gridView th{border:0px;background:#a7b7fe;color:#000000;text-align:center;font-size:18px;}
.gridView td{border:0px;padding-left:10px;}
.gridView tr:hover{cursor:pointer; background:#ffff00;}
.gridView tr:last-child:hover{ background:#000;background:#a7b7fe;}
.altRow{background:#d1daff;}
.gridPager{background:#a7b7fe;color:#000000;}
.gridPager table{margin:0px auto;}
.gridPager table td{width:20px;}
.gridPager table span{cursor:pointer;font-weight:bold;color:#1a1ac9;}
.gridPager table a{cursor:pointer;text-decoration:none;color:#000000;}
.gridPager table a:hover{text-decoration:underline;}


*********************************************************************************


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Gridview sorting and paging in Asp.Net</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <form id="form1" runat="server">
    <div>
        <%="You are viewing page "+(GridView1.PageIndex+1)+" of "+GridView1.PageCount+" ,row count "+GridView1.Rows.Count %>
        <asp:GridView ID="GridView1"
        runat="server"
        AutoGenerateColumns="false"
        AllowSorting="true"
        AllowPaging="true"
        PageSize="15"
        CssClass="gridView"
        AlternatingRowStyle-CssClass="altRow"
        PagerStyle-CssClass="gridPager"
        OnRowDataBound="GridView1_RowDataBound"
        onrowcommand="GridView1_RowCommand"
            onpageindexchanging="GridView1_PageIndexChanging" >
     
        <Columns>
         <asp:TemplateField>
         <HeaderTemplate>
             <asp:LinkButton ID="ProductId" runat="server" CommandName="ProductId">Product Id</asp:LinkButton>
         </HeaderTemplate>
         <ItemTemplate>
         <%#Eval("ProductId") %>
         </ItemTemplate>
       </asp:TemplateField>
         
         <asp:TemplateField>
         <HeaderTemplate>
             <asp:LinkButton ID="linkProductName" runat="server" CommandName="ProductName">Product Name</asp:LinkButton>
         </HeaderTemplate>
         <ItemTemplate>
         <%#Eval("ProductName")%>
         </ItemTemplate>
       </asp:TemplateField>
     
         <asp:TemplateField>
         <HeaderTemplate>
            <asp:Literal ID="litProductDetails" runat="server"></asp:Literal>
         </HeaderTemplate>
         <ItemTemplate>
         <%#Eval("ProductDetails")%>
         </ItemTemplate>
       </asp:TemplateField>
     
         <asp:TemplateField>
         <HeaderTemplate>
            <asp:LinkButton ID="linkUnitPrice" runat="server" CommandName="UnitPrice">Price</asp:LinkButton>
         </HeaderTemplate>
         <ItemTemplate>
         <%#Eval("UnitPrice")%>
         </ItemTemplate>
       </asp:TemplateField>
     
        </Columns>
 
        </asp:GridView>
    </div>
    </form>
</body>
</html>

*********************************************************************************


using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    private Products products = new Products();

    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.CellSpacing = -1;
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        GridView1.DataSource = products.ReadAll();
        GridView1.DataBind();
    }

    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridViewRow currentRow = e.Row;
            Literal litProductDetails = (Literal)currentRow.FindControl("litProductDetails");
            litProductDetails.Text = "Product Details";
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // By default, column sorted ascending(Asc) to sort descending pass (desc).
        if (e.CommandName == "ProductId")
        {
            SortGridView("ProductId","Asc");
        }
        else if (e.CommandName == "ProductName")
        {
            SortGridView("ProductName", "Asc");
        }
        else if (e.CommandName == "UnitPrice")
        {
            SortGridView("UnitPrice","Asc");
        }
    }

    private void SortGridView(String sortColumn,String sortOrder)
    {
        DataTable dt = products.ReadAll();
        DataView dv = dt.DefaultView;
        dv.Sort = sortColumn + " " + sortOrder;
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
}

********************************************************************************


using System;
using System.Web.Configuration;
public class Connection
{
public Connection(){}
     /// <summary>
     /// Read only property returns Connection string.
     /// <summary>
  public static String Cs
    {
        get
        {
            return WebConfigurationManager.ConnectionStrings["cs"].ConnectionString;
        }
    }
}

********************************************************************************

#region Namespaces
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
#endregion

/// <summary>
/// class Products
/// </summary>
 public class Products
 {

#region Private Meambers
      private SqlCommand cmd;
      private SqlConnection con;
      private SqlDataAdapter dataAdapter;
      private String ConnectionString = String.Empty;
#endregion

#region Constructor
     /// <summary>
     ///Default constructor 
     /// </summary>
      public Products()
      {
        ConnectionString=Connection.Cs;
      }

     /// <summary>
     ///Parameterised constructor 
     /// </summary>
      public Products(String connectionString)
      {
        ConnectionString=connectionString;
      }
#endregion

#region Public Methods

     /// <summary>
     /// This meathod returns all records of Products table.
     /// </summary>
     /// <returns> All rows of Products table.</returns>


      public DataTable ReadAll()
       {
        using(con = new SqlConnection(ConnectionString))
         {
          try
           {
            DataTable dt = new DataTable();
            if (con.State == ConnectionState.Closed)
            {
             con.Open();
            }
            cmd = new SqlCommand("Select * From [dbo].[Products]",con);
            dataAdapter = new SqlDataAdapter(cmd);
            dataAdapter.Fill(dt);
            return dt;
           }
           finally
            {
              if (con.State == ConnectionState.Open)
               {
                con.Close();
               }
            }
         }
      }

#endregion
 }

********************************************************************************
/*Change your web.config file*/
<connectionStrings>
<add name="cs" connectionString="Data Source=Your Data Source;Initial Catalog=softwarekaffee;Persist Security Info=True;User ID=Your User Id;Password=Your Password"/>
</connectionStrings>

********************************************************************************

/*Database Schema*/

Go
create database SoftwareKaffee

Go
use SoftwareKaffee

Go
Create table Products
(
    ProductId int identity primary key,
    ProductName varchar(50),
    ProductDetails nvarchar(200),
    UnitPrice decimal(7,2),
    Quantity int
)

Go
insert into Products values('Dell Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',55000,4)
insert into Products values( 'HCL Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',15000,30 )
insert into Products values( 'HP Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB', 23000 ,4 )
insert into Products values( 'HCL Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',35000,20 )
insert into Products values( 'Linovo Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 2GB',25000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',30000,30 )
insert into Products values( 'Dell Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',45000,10 )
insert into Products values( 'HP Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',55000,30 )
insert into Products values( 'HCL Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 2GB',35000,20 )
insert into Products values( 'Linovo Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',25000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(R) Cort(T) i5 CPU, Ra 4GB',30000,60 )
insert into Products values( 'Dell Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',35000,30 )
insert into Products values( 'HP Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',55000,30 )
insert into Products values( 'HCL Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',34000,20 )
insert into Products values( 'Linovo Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',35000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(R) Cort(T) i3 CPU, Ra 2GB',40000,30 )
insert into Products values( 'Dell Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',65000,30 )
insert into Products values( 'HP Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',75000,1 )
insert into Products values( 'HCL Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',45000,30 )
insert into Products values( 'Linovo Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',45000,30 )
insert into Products values( 'Copac Laptop','Processor Intel(RR) Cort(T2) i7 CPU, Ra 8GB',37000,5 )

No comments: