Home > ASP.NET > Databinding GridView programatically

Databinding GridView programatically

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: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: