Asp.net 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.
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 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"];
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.
That’s it we have seen, how to bind a DataTable to a GridView control.
Related Posts
No comments:
Post a Comment