In this article I will explain with an example, how to populate (bind) GridView control using SqlDataSource in ASP.Net.
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
Connection String
The following connection string has been set in the ConnectionStrings section of the Web.Config file.
<connectionStrings>
<add name="constr" connectionString="Data Source=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true" />
</connectionStrings>
HTML Markup
The following HTML Markup consists of an ASP.Net GridView control and ASP.Net SqlDataSource control.
The SqlDataSource control is set with the following properties.
1. ConnectionString – Name of the Connection String setting in the Web.Config file. Using this property the SqlDataSource will read the Connection String from the Web.Config file.
2. SelectCommand – The Select statement to fetch the records from the Customers table of the Northwind database.
The ID of the SqlDataSource control is set as DataSourceID of the GridView control
<asp:GridView ID="GridView1" runat="server" DataSourceID = "SqlDataSource1" AutoGenerateColumns = "false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$
ConnectionStrings:constr %>"
SelectCommand="SELECT TOP 10 * FROM Customers"></asp:SqlDataSource>
Screenshots
Demo
Downloads