Binding GridView using SqlDatasource in ASP.NET


With GridView we can display an entire collection of data, add sorting and paging, and perform inline editing.


The SqlDataSource control is the data source control to use if your data is stored in a SQL Server, SQLServer Express, Oracle Server, ODBC data source, OLE DB data source, or Windows SQL CE Database.


Displaying Data with the GridView

 

Default.aspx

  <%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="emp_id" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="emp_id" HeaderText="emp_id" ReadOnly="True"
                    SortExpression="emp_id" />
                <asp:BoundField DataField="fname" HeaderText="fname" SortExpression="fname" />
                <asp:BoundField DataField="lname" HeaderText="lname" SortExpression="lname" />
                <asp:BoundField DataField="hire_date" HeaderText="hire_date"
                    SortExpression="hire_date" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
            SelectCommand="SELECT top 10 [emp_id], [fname], [lname], [hire_date] FROM [employee]">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

web.config
<?xml version="1.0"?>

<configuration>

  <appSettings/>
  <connectionStrings>
    <add name="pubsConnectionString" connectionString="Data Source=spde670;Initial Catalog=pubs;User ID=sa;Password=sql2005" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>

    <compilation debug="true"/>
    
    <authentication mode="Windows"/>
  </system.web>
</configuration>

Output