Binding GridView with Data - The ADO.NET way

This example demonstrates how to populate GridView with data from the database using the ADO.NET way.
Before you proceed reading this example be sure that you know the basics of ADO.NET manipulation. If you are not familiar with ADO.NET then I would suggest you to refer at the following link below:

ADO.NET Tutorial

STEP 1: Setting up the Connection String

- Open your Web.config file and set up your connection string like below:

<connectionStrings> <add name="MyDBConnection" connectionString="Data Source=WPHVD185022-9O0; Initial Catalog=Northwind; Integrated Security=SSPI;" providerName="System.Data.SqlClient"/> </connectionStrings>

STEP 2: Create the GetConnectionString() method

- Create a method for accessing your connection string that was set up at the Web.config file

private string GetConnectionString(){ return ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString; }

Note: MyDBConnection is the name of the connectionstring that was set up in the webconfig.

STEP 3: Setting up the GridView in the mark up (ASPX)

- Grab a GridView from the Visual Studio ToolBox and then Set AutoGenerateColumns to False.
- Add BoundField Columns in GridView and set the DataField and the HeaderText accordingly. See below:

Populating GrindView Control

STEP 4: Create the BindGridView() method

- After setting up your GridView in the mark up then switch back to Code behind
- Declare the following NameSpace below so that we can use the SqlClient built-in libraries

using System.Data.SqlClient;

-Create the method for Binding the GridView

private void BindGridView() {

    DataTable dt = new DataTable();
    SqlConnection connection = new SqlConnection(GetConnectionString()); 

    try
    {
      connection.Open();
      string sqlStatement = "SELECT \* FROM Customers";
      SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
      SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
      sqlDa.Fill(dt);

          if (dt.Rows.Count > 0)
          {
            GridView1.DataSource = dt;
            GridView1.DataBind();
          }
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
    }
    finally
    {
        connection.Close();
    }

}

STEP 5: Calling the BindGridView() method on initial load of the page.

protected void Page_Load(object sender, EventArgs e){ if (!Page.IsPostBack){ BindGridView(); } }

STEP 6: Displaying the Output in the page

- Compile and run your page to see the output.. see below

GridResult

That simple!

This article is part of the GWB Archives. Original Author: Vincent Maverick Durano

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.