Friday, May 4, 2012

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

The GridView accepts many types of datasources like DataTable, DataReader, 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

Font-Bold="true" />
ForeColor="Black" />
ForeColor="Black" />


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 the GridView

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"];

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 form in the GridView control.

That’s it we have seen, how to bind a DataTable to a GridView control.

Related Posts

Search Flipkart Products:

No comments: