How To Populate GridView From Code Behind
How To Populate GridView From Code Behind
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;
{
if (!IsPostBack)
{
GetData();
}
}
private void GetData()
{
DataTable table = new DataTable();
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.