Gridview Paging using C#

Updated on 14 Sep 2012,
Published on 13 Mar 2008

A GridView is most often used to display the data retrieved from the database in Tabular form with features of Gridview like data paging, sorting and auto formats.

You can use C# code to bind the SQL data with GridView control and follow the following simple steps to make your ASP.Net GridView control with paging enabled.

GridView Examples:

You can see the live samples and examples of GridView Control from the following links:

First of all drag the GridView control from Data controls menu. It will add the GridView control HTML source code as given above. Now click on GridView control to load the control properties at right side panel.

<asp:GridView id="GridView1" runat="server"></asp:GridView>

To enable the paging in GridView control select True from the dropdown list of AllowPaging property of GridView control as shown in the above image.

It will add AllowPaging="True" in HTML source code of Gridview.

Next step is to bind the data with Gridview control and handle the GridView paging event.

To bind the PageIndexChanging of GridView control, double click on the PageIndexChanging event in the properties of Gridview. It will add the event in HTML source code as well as C# code.

HTML source code for GridView Control

<asp:GridView ID="GridView1" 
              runat="server"
              CellPadding="2"
              AllowPaging="True" 
              PageSize="10"
              OnPageIndexChanging="GridView1_PageIndexChanging" 
              AutoGenerateColumns="False" 
              Width="500px">
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="ProductID">
            <HeaderStyle HorizontalAlign="Left" />
        </asp:BoundField>

        <asp:BoundField DataField="ProductName" HeaderText="Product Name">
            <HeaderStyle HorizontalAlign="Left" Width="200px" />
        </asp:BoundField>

        <asp:BoundField DataField="UnitsInStock" HeaderText="Units In Stock">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:BoundField>

        <asp:BoundField DataField="UnitPrice" HeaderText="Price Per Unit">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:BoundField>
    </Columns>
</asp:GridView>

You can set the PageSize value as per your requirement. 

C# Code Sample

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            bindGridView();
    }

    public void bindGridView()
    {
        // string variable to store the connection string
         // defined in ConnectionStrings section of web.config file.
        string connStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

        // object created for SqlConnection Class.
        SqlConnection mySQLconnection = new SqlConnection(connStr);

        // if condition that can be used to check the sql connection
        // whether it is already open or not.
        if (mySQLconnection.State == ConnectionState.Closed)
        {
            mySQLconnection.Open();
        }

        SqlCommand mySqlCommand = new SqlCommand("select ProductID, ProductName, UnitsInStock, UnitPrice from products", mySQLconnection);
        SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
        DataSet myDataSet = new DataSet();
        mySqlAdapter.Fill(myDataSet);

        GridView1.DataSource = myDataSet;
        GridView1.DataBind();


        // if condition that can be used to check the sql connection
        // if it is open then close it.
        if (mySQLconnection.State == ConnectionState.Open)
        {
            mySQLconnection.Close();
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        bindGridView();
    }

After data binding with GridView control you will get the results as shown in the live sample of Gridview control on page load.

Output:

Get the output of above discussed code from the following link:

ASP.Net GridView Paging

Next tutorial: ASP.Net 2.0 Gridview Sorting Using C# provides the C# code and example of sorting feature of gridview control.

69 Responses to "Gridview Paging using C#"
suresh
This very useful for me
jayaram
Thanks & please upload all the coding for editing and deleting also.
Tamojit Chakraborty
Wonderful and Helpful Article on Paging A GridView
Tatolo
Thanks a lot very helpful article!
venkat kumar.karra
This is very usefull artical for freshers and all.
Thankq very much.
Harsha
Very good & simple work.
Helped me a lot.
Plz post the code for sorting also :)
a
I have a Data set which in which i am getting data twice from tow different tables one is clients and another is organization table and in the select statement i have made the no and names of the column similar now i have bindied a grid view with this data set all is fine till here the now i apply paging to this grid the paging is working fine till the page contains data from the first table but it displays the last page of the first table if the page index related too second tables are clicked any help will be highly appreciated
aditi
awesome code.....thanks a ton....
TMK
I tried in 2005,But gv.PageIndex = e.NewPageIndex; is not availabe and it shows error when compile .

In 2003 , its working fine.

Anyway thanks. .
somanath
hats off BOSS,

thanks a lot. it was really helpful.
Hi, Thanks for this nice tutorial. It helped me a lot.
dipak
Hats off
Very good & simple work.
Helped me a lotttttttttttttt

Raphael
Dude, sweet solution, simple and very straight to the point. Very KISS, I like it. Salute!
Lanton
Thank you.
ram
It's useful but that previous button is not working. And also if i use same Grid View for different purpose then how to handle it.
ram
Hi, I have some data controls like Grid view,Text box . My Question is that is it possible that if on web page the mouse pointer moves on text and the text specific words will be highlighted and if we click on that highlighted word it will show some more information about that word .You can consider it like a Dictionary(Actually it's not dictionary but simply user friendly)that if i search some word in document then it highlights that words where ever it comes then we are going to show more detail according to specific word that user has clicked. If you know how to do that please tell me i need it in my application desperately. Thanks for your valuable time for it.Hope You will be there with more information.Bye Have a Nice Day.
Dhiraj
Thanks for nice article.
NaREN
Thanks man.....
Prasanth
Yep...lolz....thnkz a lot
Sailaja
Thanks a lot... Really nice
vinod
thanx
Hiki
Nice article.. thanks a lot, this is easily understandable to start with.
Very Good article
J Morris
I am getting the error "No overload for method 'bindGridView' takes '0' arguments". What am I missing in the method?
Shivam Gupta

very good artical, very useful
Sebastian Boyd
Muy bueno. Me fue de mucha utilidad. gracias!!!
Easy and great :)
It's useful but that previous button is not working. And also if i use same Grid View for different purpose then how to handle it.
i think this is to the point code. nice
JP
Hi,

i have some bounded columns in gridview and adding new columns at run time, when i change the value of previous columns then all component of gridview get lost and only gridview lines appears, can someone help me t solve this problem
mohammad
thanks u alot
Sunaina
Thanks alot
sonika
i have followed all the steps mentioned above but it could not shows the page index at the runtime.but for this i used the templatefield
That was great, thank you very much
Tanuj Sharma
nice code well done
Shweta
Simple and useful explantion...
Jonny
Thank you very much! I have been searching for this all morning and this was the first website with working code :)
Manju
Ya its working well
vishal
thankkkkkkkkkkkkkkkkkkk uuuuuu SOoooooooooooooooooooo much...... its working...... very nice work....
Thanks good article,Thank you
praneeth
thanks it worked for me
Gameturner
Thanks a lot. It worked.\m/
charles
Hmmm....This is lovely. It works! Thanks a lot!
Thanks a lot :) It worked well ... So cool :)
jean
nice...=) it really works...thanks!!
khyati
superbly great..i tried mostly options..but this one works..thanks a lot
Venkat
It is very helpful to all who are learning .net and i appreciating you a lot.
Karu
excellent and easy way thanks
Vikas
Thank u ..............
I use VS 2010 Pro on Oracle 11g. This worked without any issues. I have also included column sorting by accepting a parameter in bindGridView code. Thanks for the nice article.
krishna
ya this one is working good, but i want how to delete or clear date in grid view by using clear/delete button using c# code reply as soon as possible
Ezineasp.net
@Krishna You can get the code for delete command here: http://www.ezineasp.net/post/ASP-Net-Gridview-Confirm-Delete-Using-Javascript-with-C-sharp-Code.aspx
yoshikuni
Thanks a lot
vijay
simple and Superb!!!
Anuja
thanks for the article.....
thanks
Narender
Thanks you sir
Grid view is used for display purpose that was comes from database allow paging and sorting is the most important to me.
Homer Ubuntu
Thanks!
merci bq c'est vraiment utile
Ronnel Sevilla
What if combination of paging and sorting?
Nice article. Also check this link for Editing and Delete GridView rows in Asp.Net. http://www.encodedna.com/2013/01/asp.net-gridview-edit-delete.htm Its a very simple article. Regards Arun
Asma
i used same code for paging but by clicking in next page it does not show any thing....what can i do now????
Kath
Thank you so much !
Modin
Thanx Bro
sachin
Hello, I did everything as specified. I wrote pageIndexChanging event also.. But after clicking on next page number, page is not loading. Plz help...
kg
thank you
taigrom
Thanks, brow!
Ramin
I'm Iranian Thank you so much sir For This Article!
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email