How to bind GridView control with SqlDataSource control

During application development there will be many occasions to display database records on a web page. Records are displayed after retrieving them from a Sql database. To do so, we need to use one DataSource control and one DataBound control. We use the DataSource control -SqlDataSource control to access the data from the Sql server database. The DataBound control we use to display the records is the GridView control.

pictorial representation of how the gridview control is connected to the sqldatasource control and the role of connection string property and select command property

There are two steps to bind a GridView control with SqlDataSource control. The first step is to configure the SqlDataSource control. Configuring the SqlDataSource control involves setting the ConnectionString property and SelectCommand property. These are the minimum steps required to configure the SqlDataSource control.

The next step is to bind the GridView control to the data source by setting its DataSourceID property to the ID of SqlDataSource control. The example below shows how to bind a GridView control to the SqlDataSource control.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$Connectionstrings:ERPConnectionString%>"
SelectCommand="SELECT * FROM AccountsTable">
</asp:SqlDataSource>  
<asp:GridView ID="GridView1"  DataSourceID="SqlDataSource1"  
AutoGenerateColumns="true" runat="server">
</asp:GridView>


The ConnectionString property of the SqlDataSource control specifies how to connect to the database. This property can be a hard-coded connection string or can point to a connection string in a Web.config file as shown in the code given above. The SelectCommand property specifies the SQL statement to execute to retrieve the data.

»  What is a GridView




Authorship By Bharati Karedla