Archive

Posts Tagged ‘sqldatasource’

Databinding GridView using SqlDataSource

December 6, 2010 1 comment

The GridView control in ASP.NET is a control that displays the data that you selected from the database in a form of a table where each row represents a record in the database. GridView also allows you to select, update, delete, and sort the data.

In addition, GridView also allows you to customize how the data is to be represented to the user when the data is binded from the database.

Here, I’ll show you how to bind data into the GridView control using SqlDataSource control as the data source.

 

Assumptions:
I assume you already have a ready database that have a Customers table. Also you have pre-define a connection string in your web.config file.

 

Code for ASPX Page:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebDemo_VB.Web._GridView_SqlDataSource_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 runat="server" ID="GridView1" AutoGenerateColumns="False" DataKeyNames="CustomerID"
            DataSourceID="SqlDataSource1" EnableModelValidation="True">
            <Columns>
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="StaffID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
                <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
            SelectCommand="[CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

The code above shows a simple method on how to data bind the GridView to display information from the Customers table in the database. This is the most simple way of data binding a GridView control.

Note: For advanced data binding and customization method, please wait/see the later post.