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.


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" "">

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" DataKeyNames="CustomerID"
            DataSourceID="SqlDataSource1" EnableModelValidation="True">
                <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" />
        <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
            SelectCommand="[CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]">

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.