How To Populate GridView From Code Behind

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

How to populate GridView from code behind?

In this article, we shall learn how to populate GridView from code behind. This tutorials is for beginners.

Introduction
GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination.
It also allows us to manipulate the data as well.
Working with the Code
Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.
In order to populate GridView from the code behind using a data source, we can follow this approach.
Below is my ASPX code that contains a simple GridView.
ASPX PAGE
<asp:GridView ID="GridView1" runat="server" />
In the above code we have simply kept a GridView control with runat server and id attributes.
CODE BEHIND
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)

{
if (!IsPostBack)
{
GetData();
}
}
private void GetData()
{
DataTable table = new DataTable();

// get the connection


using (SqlConnection conn = new SqlConnection(_connStr))
{
// write the sql statement to execute
string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM
PersonalDetail ORDER By AutoId";
// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))


{
// get the adapter object and attach the command object to it
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
// fire Fill method to fetch the data and fill into DataTable
ad.Fill(table);
}
}
}
// specify the data source for the GridView
GridView1.DataSource = table;
// bind the data now
GridView1.DataBind();
}

In the code behind, we have used ADO.NET objects to retrieve the data from the database to a DataTable and that DataTable
(table variable) is being used as theDataSource for the GridView. Just setting the DataSource is not enough; we need to call
the DataBind method of the GridView that actually binds the data to the GridView.

You might also like