In ASP.NET web forms, GridView Control plays the major role to display data in tabular form,  we can also bind it with database table data and edit/add more data. So, in this article, I have explained how we can use Gridview in asp.net web form to show database table data in it.

Gridview in ASP.NET Web-Forms(.ASPX)

Gridview is a control in asp.net, that displays the values of a data source(SQL server database) in a tabular form where each column represents a field and each row represents a record. The GridView control also enables you to select, sort, and edit these items.

The GridView control supports the following features:

  • Binding to data source controls, such as SqlDataSource.
  • Built-in sort capabilities.
  • Built-in update and delete capabilities.
  • Built-in paging capabilities.
  • Built-in row selection capabilities.
  • Programmatic access to the GridView object model to dynamically set properties, handle events, and so on.
  • Multiple key fields.
  • Multiple data fields for the hyperlink columns.
  • Customizable appearance through themes and styles.

Connecting GridView to bind data in ASP.NET

Let's create a new project in Visual Studio (I am using Visual Studio Community 2017 version),

Step 1: Navigate to File-> New -> Project->Select "ASP.NET Web Application" from right pane and Select "Web" from left pane

then on the next screen, Select Empty project, but check "Web-Forms", and click "Ok".

Step 2: Now, create a new Web-Form page, Right-Click on your Project name in the Solution Explorer, Select "Add", then Select "New item", from list select "Web Form" and name it "Default.aspx"

In the newly added .aspx page, we will create grid view using the code below, or you can simply drag and drop it from "Toolbox' on the left of Visual Studio

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
            OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
            <Columns>
                <asp:BoundField  DataField="PersonType" HeaderText="Person Type" />
                <asp:BoundField  DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField  DataField="LastName" HeaderText="Last Name" />
               
            </Columns>
        </asp:GridView>

In the above code, we have added GridView Control, but with that, we are also allowing paging in this gridview by using "AllowPaging= True" and calling method " OnPageIndexChanging="OnPageIndexChanging"" , each page will show 10 rows so "PageSize =10"

We have also added Columns of the table, which are

       <Columns>
                <asp:BoundField  DataField="PersonType" HeaderText="Person Type" />
                <asp:BoundField  DataField="FirstName" HeaderText="First Name" />
                <asp:BoundField  DataField="LastName" HeaderText="Last Name" />
               
            </Columns>

Where, DataField=  Columnd name from datatable table, which need to be binded

HeaderText= Column header text to be show in table.

We will be using AdventureWorks2012 database table Person's data in this GridView, which looks something like this

/sample-database-table-gridview-asp-net-example-min.png

Step 3: Create the C# Code in Code behind to load data from database in the gridview, so naviagte to "Default.aspx.cs" and use the code below

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

        private void BindGrid()
        {
            string constr = @"Data Source=DESKTOP-U5CMQ7M\SQLEXPRESS;Initial Catalog='AdventureWorks2012';Integrated Security=True";
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT PersonType, FirstName, LastName FROM Person.Person"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
        }

Inside the Page Load event of the page, the GridView is populated with records from the Perons table of the AdventureWorks2012 database.

Implement paging in GridView

To implement paging, we will add the below method in Default.aspx.cs

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.BindGrid();
}

The value of the PageIndex of the Page which was clicked is present inside the NewPageIndex property of the GridViewPageEventArgs object and it is set to the PageIndex property of the GridView and the GridView is again populated by calling the BindGrid function.

So, the complete Default.aspx.cs code will look like this

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

namespace GridViewExample
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindGrid();
            }
        }

        private void BindGrid()
        {
            string constr = @"Data Source=DESKTOP-U5CMQ7M\SQLEXPRESS;Initial Catalog='AdventureWorks2012';Integrated Security=True";
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT PersonType, FirstName, LastName FROM Person.Person"))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        cmd.Connection = con;
                        sda.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
        }


        protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

    }
}

That's it, we are done, you can now build and run your project in the browser, you should see output like below

gridview-asp-net-example-with-paging-min.gif

In the above output, as you can see we have implemented GridView in ASP.NET Web-Forms with pagination.

You might also like to read:

Search (Filter) Records in ASP.NET GridView with Textbox (Highlighting searched term)

Bind Data to Gridview using jQuery Ajax & WebMethod in ASP.NET

Read Excel file and import data into GridView using Datatable in ASP.NET

Creating GridView in ASP.Net Core MVC

Complete C# Tutorial