How to use PageSize and Onselectedindexchanged in GridView in ASP.NET

I am showing you a simple example so that you are able to understand it properly. Just follow all the given points and you will be able to understand the code properly. It's too easy.

Note - First, observe the following required point

AllowPaging ="true" in gridview tag
AutoPostBack ="true" in dropdownlist

Step 1: Now, open a new website and take the new page as a GridviewExample.aspx. Write the following code:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <asp:button id="btntest" runat="server" text="test" onclick="btntest_Click1" />

    <br />

    Enter pageSize:

    <asp:dropdownlist id="dropdownlist1" runat="server" autopostback="true" onselectedindexchanged="dropdownlist1_SelectedIndexChanged">

<asp:ListItem>10</asp:ListItem>

<asp:ListItem>20</asp:ListItem>

<asp:ListItem >30</asp:ListItem>

<asp:ListItem >50</asp:ListItem>

</asp:dropdownlist>

    <asp:gridview id="gv1" runat="server" allowpaging="true" onpageindexchanging="gv1_PageIndexChanging"

        onselectedindexchanged="gv1_SelectedIndexChanged">

</asp:gridview>

    </form>

</body>

</html>

Step 2: C# code: (GridviewExample.aspx.cs)

// this is button

protected void btntest_Click1(object sender, EventArgs e)

{

    showData();

}

protected void showData() // create a method to show data

{

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

    SqlDataAdapter da = new SqlDataAdapter("select * from invoice", con);

    DataTable dt = new DataTable();

    da.Fill(dt);

    gv1.PageSize = int.Parse(dropdownlist1.SelectedValue);

    gv1.DataSource = dt;

    gv1.DataBind();

    Session["mydata"] = dt; // here i have created session of data

}

protected void showSessionData() // create another method to display sessioned data

{

    gv1.PageSize = int.Parse(dropdownlist1.SelectedValue);

    DataTable dt = (DataTable)Session["mydata"];

    gv1.DataSource = dt;

    gv1.DataBind();

}

protected void gv1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

    gv1.PageIndex = e.NewPageIndex;

    showSessionData();

}

protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)

{

     showSessionData();

    //don't call datashow() method in this call only showsessionData();

} 

Step 3: See your web.config file

<connectionStrings>

  <add name="constr" connectionString="Data Source=ashok;

Initial Catalog=ashokdb;

Integrated Security=True" providerName="System.Data.SqlClient"/>

</connectionStrings>

Step 4: Run successfully