21 September 2012

Binding a DataTable to GridView

Asp.net provides a GridView controls to display table data in Asp.Net pages, the GridViewneeds to be provided with data to populate the same in the UI.

The GridView accepts many types of datasources like DataTableDataReader, List etc, today we shall see on how to bind the data from a DataTable to a GridView control.


Refer the post Binding a C# List to a GridView control, to Bind a List to the GridView.

First we need to define the GridView control in the .aspx page, here is the code

<asp:GridView
ID="grdUsers"
runat="server"
AutoGenerateColumns="true">
   
<HeaderStyle
BackColor="Navy"
ForeColor="White"
Font-Bold="true" />
   
<RowStyle
BackColor="White"
ForeColor="Black" />
   
<AlternatingRowStyle
BackColor="Wheat"
ForeColor="Black" />

</asp:GridView>

Once we are done with the declaration of the GridView tag, we can switch to the code behind file (.cs/.vb file) to implement the DataBinding logic. Here is the code to bind data to theGridView

string strSQL = "SELECT * FROM USERS";
DataSet dsUsers = new DataSet();
dsUsers = DataAccessLayer.GetDataSet(strSQL, "dtUSers");
//
// Implement your own DataAccess logic here to get data from the DB.
//
grdUsers.DataSource = dsUsers.Tables["dtUSers"];
grdUsers.DataBind();

The DataSet & DataTable objects are present in the System.Data Assembly; hence make sure that a reference to this assembly is added to the project before building the Project.
Build and run the project, you will be able to see the result of the query displayed in the Asp.net form in the GridView control.