Search This Blog

Tuesday, July 22, 2014

Paging in GridView

In .aspx file :

<asp:GridView ID="GridView1" runat="server" PageSize="5" AllowPaging="true"         onpageindexchanging="GridView1_PageIndexChanging">
<PagerSettings Mode="Numeric" />
</asp:GridView>

In .aspx.cs file :

public partial class ADO_DATACONTROLS_Paging : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //sspi=Security Support Provider Interface ~= trusted connection
        if(!IsPostBack)
            DisplayEmployees();
    }

    private void DisplayEmployees()
    {
        string strcn = "data source=ADMIN-PC\\SQLEXPRESS;initial catalog=db17;integrated security=sspi";
        SqlConnection cn = new SqlConnection(strcn);
        SqlCommand cmd = new SqlCommand("select * from employees", cn);
        try
        {
            cn.Open();
            DataSet ds = new DataSet();
            SqlDataAdapter DA = new SqlDataAdapter(cmd);
            DA.Fill(ds);
            Session["ds"] = ds;
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (SqlException ex)
        {

        }
        finally
        {
            cn.Close();
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        DataSet ds = (DataSet)Session["ds"];
        DataTable dt = ds.Tables[0];
        GridView1.DataSource = dt;
        GridView1.PageIndex = e.NewPageIndex;//this code must be written between Datasource and DataBind
        GridView1.DataBind();
    }
}

Table structure:

eidfnamelnameagesalarydeptdoj
1rajeevsukla2312000.net23-Oct-11 12:00:00 AM
2sowmyakumari2319000db13-Nov-10 12:00:00 AM
3kishorekumar2736000android16-Oct-11 12:00:00 AM
4abimanyubiswal22nullandroid20-Feb-10 12:00:00 AM
5sonikumar2421800.net21-Jun-09 12:00:00 AM
6anu_singh2212000db23-Oct-10 12:00:00 AM
7_dineshmoh%anty2315000.net26-Aug-09 12:00:00 AM
8nishala_kumari2218000db19-Jul-08 12:00:00 AM
1rajeevsukla2312000.net23-Oct-11 12:00:00 AM

No comments: