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 the DataSource 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.
OUTPUT

When we run the page, the output looks something similar to the above picture (naturally if your data will be exactly same as mine ;)).
In the next couple of articles, we shall learn customization of GridView and many other frequently faced problem solutions related with the GridView.
Keep reading and sharing your knowledge.