Archive

Posts Tagged ‘databinding’

Databinding GridView programatically

December 7, 2010 Leave a comment

In my previous post, I’ve showed how to bind data to GridView using SqlDataSource. Here, I’ll show how to bind data to GridView using code behind.

 

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="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebDemo_CS.Web.Data.GridView.DatabindProgramatically.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>Databind GridView Programatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            Databind GridView Programatically</h1>
        <asp:Label runat="server" ID="Label1" ForeColor="Red" />
        <br />
        <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="true">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code for C#:

protected void Page_Load(object sender, EventArgs e)
        {
            // This example uses Microsoft SQL Server and connects
            // to the Northwind sample database. The data source needs
            // to be bound to the GridView control only when the
            // page is first loaded. Thereafter, the values are
            // stored in view state.                     
            if (!IsPostBack)
            {
                // Declare the query string.
                String queryString = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";

                // Run the query and bind the resulting DataSet
                // to the GridView control.
                System.Data.DataSet ds = GetData(queryString);
                if (ds.Tables.Count > 0)
                {
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
                else
                {
                    Label1.Text = "Unable to connect to the database.";
                }
            }
        }

        System.Data.DataSet GetData(String queryString)
        {
            // Retrieve the connection string stored in the Web.config file.
            String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

            System.Data.DataSet ds = new System.Data.DataSet();

            try
            {
                // Connect to the database and run the query.
                System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString);
                System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(queryString, connection);

                // Fill the DataSet.
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
                // The connection failed. Display an error message.
                Label1.Text = "Unable to connect to the database.";
            }

            return ds;
        }

Code for VB.NET:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ‘ This example uses Microsoft SQL Server and connects
        ‘ to the Northwind sample database. The data source needs
        ‘ to be bound to the GridView control only when the
        ‘ page is first loaded. Thereafter, the values are
        ‘ stored in view state.                     
        If Not IsPostBack Then

            ‘ Declare the query string.
            Dim queryString As String = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"

            ‘ Run the query and bind the resulting DataSet
            ‘ to the GridView control.
            Dim ds As DataSet = GetData(queryString)
            If (ds.Tables.Count > 0) Then
                GridView1.DataSource = ds
                GridView1.DataBind()
            Else
                Label1.Text = "Unable to connect to the database."
            End If

        End If
    End Sub

    Protected Function GetData(ByVal queryString As String) As DataSet
        ‘ Retrieve the connection string stored in the Web.config file.
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
        Dim ds As New DataSet()

        Try
            ‘ Connect to the database and run the query.
            Dim connection As New System.Data.SqlClient.SqlConnection(connectionString)
            Dim adapter As New System.Data.SqlClient.SqlDataAdapter(queryString, connection)

            ‘ Fill the DataSet.
            Adapter.Fill(ds)

        Catch ex As Exception
            ‘ The connection failed. Display an error message.
            Label1.Text = "Unable to connect to the database."
        End Try

        Return ds
    End Function

Conclusion:

Data bind data into GridView from code behind provides more flexibility as you can control the data to be selected from the database dynamically.

Advertisements
Categories: ASP.NET Tags: , ,

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.