Click here to Skip to main content
Click here to Skip to main content

Easily use ADO in DataGrids, DropDown Lists

, 12 Nov 2004
Rate this:
Please Sign up or sign in to vote.
An article on easily binding ADO data to control using reusable code.

Introduction

ADO is a very powerful way of getting data out of a database, but it's also very confusing, and there are numerous techniques and connection methods of getting your data onto a DataGrid or other controls. The approach I took was to standardize and develop reusable compartmented code to access databases and display data. I've written ASP.NET pages that can access limitless SQL queries for displaying results in limitless DataGrids.

This Article will describe how I use reusable code for connecting to ADO data and display the resulting data in DataGrids and other controls. I will also describe how to develop your own code for similar tasks.

Background

This article assumes that you have knowledge of C#, SQL, ADO and .NET controls.

I use the NorthWind database in the demo code but it can be altered to use any database.

Using the code

Web.Config

I use the <appSettings> in the web.config to store strings that are used in the application. If you've never used application settings in web.config then do try; I generally use web.config to store database connection information for the simple reason that it can be quickly and easily changed for the whole project and makes code / project a lot more portable.

 <appSettings>
  <add key="dsn_SQL" 
    value="SERVER=localhost;uid=myuser;password=pass;DATABASE=NorthWind;"/>
</appSettings>

DataGrid.aspx.cs

Below is the complete code for the DataGrid.aspx page. In a nutshell, the BindGrid() function connects to the database and displays the resulting data in the DataGrid.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;

namespace Easy_ADO_Binds
{
  public class WebForm1 : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.DataGrid DataGrid1;
    // Get the SQL Connection string from the web.config.
    public String strConnectSQL = 
      (ConfigurationSettings.AppSettings["dsn_SQL"]);

    private void Page_Load(object sender, System.EventArgs e)
    {
      // Build SQL String
      string SQLstring = "Select * FROM Employee";

      // Call and Build Grid
      // BindGrid(SQLDBcontectString, SQLstring, DataGrid);
      BindGrid(strConnectSQL, SQLstring, DataGrid1 );
    }

    private void BindGrid(string DBconnectString, string sqlCommand, 
                           System.Web.UI.WebControls.DataGrid DGrid)
    // Load intial page from database
    // binds to datagrid
    {
      // create data connection
      SqlConnection conn = new SqlConnection(DBconnectString);

      // Call SQL from db
      SqlCommand command = new SqlCommand(sqlCommand, conn);

      // create data adapter
      SqlDataAdapter adapter = new SqlDataAdapter(command);

      // create and fill dataset
      DataSet ds = new DataSet();
      adapter.Fill(ds);

      // fill and bind data to Datagrid
      DGrid.DataSource = ds;
      DGrid.DataBind();
      // Close Connection
      conn.Close();
    }

#region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }

    private void InitializeComponent()
    {
      this.Load += new System.EventHandler(this.Page_Load);
    }
#endregion
  }
}

Get the SQL String From the Web.Config

This will allow you to pick your string up from the web.config, neat eh? I use this for specifying database connections, reporting servers, default URL string for home or linked projects, and any other global strings.

using System.Configuration;
// Get the SQL Connection string from the web.config.
public String strConnectSQL = (ConfigurationSettings.AppSettings["dsn_SQL"]);

private void BindGrid()

This is the business end of the project. I drop this code into any page I wish to fetch and display data from my database to my DataGrid. I don't have to write complex C# or ADO code. Drop it in, pass DB, SQL, DataGrid parameters, and it goes get the data for me.

How BindGrid() works

You pass BindGrid() a database connection, SQL string, and the DataGrid ID, and it goes off, makes the connection to your database, runs the SQL command, and displays the data in a DataGrid.

  • BindGrid( db, SQL, DataGrid)
  • BindGrid( "Tell Me What Database", "Tell Me What SQL you want to run", "Tell Me What DataGrid you want to display the data in")

BindGrid Inputs

private void BindGrid(string DBconnectString, 
   string sqlCommand, System.Web.UI.WebControls.DataGrid DGrid)
  • string DBconnectString: Database
  • string sqlCommand: SQL
  • System.Web.UI.WebControls.DataGrid DGrid: DataGrid

Note: you can specify a Web Control as an input for a function in C#. All you have to do is specify what DataGrid ID you want the function to act on.

private void BindGrid(string DBconnectString, 
      string sqlCommand, System.Web.UI.WebControls.DataGrid DGrid)
// Load intial page from database
// binds to datagrid
{
  // create data connection 
  SqlConnection conn = new SqlConnection(DBconnectString);

  // Call SQL from db 
  SqlCommand command = new SqlCommand(sqlCommand, conn);

  // create data adapter
  SqlDataAdapter adapter = new SqlDataAdapter(command);

  // create and fill dataset 
  DataSet ds = new DataSet();
  adapter.Fill(ds);

  // fill and bind data to Datagrid
  DGrid.DataSource = ds;
  DGrid.DataBind();
  // Close Connection
  conn.Close();
}

Calling BindGrid()

The function BindGrid() defines:

  • Database connection string: as specified in the Web.Config
  • SQL String: any SQL string, even stored procedures can be specified here.
  • DataGrid: The ID of the DataGrid.
private void Page_Load(object sender, System.EventArgs e)
{
  // Build SQL String
  string SQLstring = "Select * FROM Employee";

  // Call and Build Grid
  // BindGrid(SQLDBcontectString, SQLstring, DataGrid);
  BindGrid(strConnectSQL, SQLstring, DataGrid1 );
}

Populating Multiple DataGrids

Say you wanted to populate three DataGrids supplied by different SQL Commands. Just call the BindGrid() three times with different SQL commands as shown below. So you are now using the same code to populate multiple DataGrids.

// DataGrid 1
string SQLstring1 = "Select * FROM Employee";
BindGrid(strConnectSQL, SQLstring1, DataGrid1 );

// DateGrid 2
string SQLstring2 = "Select * FROM Customers";
BindGrid(strConnectSQL, SQLstring2, DataGrid2 );

//DataGrid3
string SQLstring3 = "Select * FROM Orsders";
BindGrid(strConnectSQL, SQLstring3, DataGrid3 );

Make a BindList()

OK. We are going to alter the BindGrid() code to make a BindList() that will populate a ASP.NET DropDownList.

The code is a bit more complicated as the DropDownList has two more properties you have to specify:

  • DataTextField: What is displayed in the dropdown list and what the user sees.
  • DataValueField: The value used by your code to determine the user choice.

These values are added to the input parameters of BindList(), so running it goes like this:

BindList(db, SQL, Text, Value, DropDownList);
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;

namespace BindList
{
  public class WebForm1 : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.DropDownList DropDownList1;
    // Get the SQL Connection string from the web.config.
    public String strConnectSQL = 
        (ConfigurationSettings.AppSettings["dsn_SQL"]);

    private void Page_Load(object sender, System.EventArgs e)
    {
      // Build SQL String
      string SQLstring = "Select EmployeeID, FirstName + ' ' + LastName" + 
                         " as name FROM Employees";
      string TextField = "name";
      string ValueField = "EmployeeID";

      BindList(strConnectSQL, SQLstring, TextField , 
                              ValueField, DropDownList1 );
    }

    private void BindList(string strConnectSQL, string SQLstring, 
            string TextField, string ValueField, 
            System.Web.UI.WebControls.DropDownList Dlist)
    {
      SqlConnection myConnection = new SqlConnection(strConnectSQL);
      SqlCommand myCommand = new SqlCommand( SQLstring, myConnection );
      myConnection.Open();

      Dlist.DataSource = myCommand.ExecuteReader();
      Dlist.DataTextField = TextField;
      Dlist.DataValueField = ValueField;
      Dlist.DataBind();

      myConnection.Close();
    }

#region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }

/// <span class="code-SummaryComment"><summary>
</span>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// <span class="code-SummaryComment"></summary>
</span>
    private void InitializeComponent()
    {
      this.Load += new System.EventHandler(this.Page_Load);
    }
#endregion
  }
}

Points of Interest

One of the best things I've learned doing this is that you can specify web controls as input parameters for functions in ASP.NET. This has certainly changed my coding habits and I'm now developing more generic reusable code.

Why Use this Code

It's really simple. Once written for a particular control, you never have to write it again. You can use the same code again and again.

History

V1.1 Nov 2004

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Frank Kerrigan
Software Developer (Senior)
United Kingdom United Kingdom
Frank Kerrigan
 
Currently developing Insurance systems with SQL Server, ASP.NET, C#, ADO for a company in Glasgow Scotland. Very keen on OOP and NUNIT testing. Been in IT forever (20 years) in mix of development and supporting applications / servers. Worked for companies big and small and enjoyed both.
 
Developed in (newest first) : C#, Progress 4GL, ASP.NET, SQL TSQL, HTML, VB.NET, ASP, VB, VBscript, JavaScript, Oracle PSQL, perl, Access v1-2000, sybase/informi, Pic Controllers, 6502 (ask your dad).
 
Msc .Net Development Evenings www.gcu.ac.uk
MCAD Passed
MCP C# ASP.NET Web Applications
MCP SQL Server 2000
HND Computing
OND / HNC Electrical Engineering,
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 3 Pinmembermeso8711-Oct-10 3:48 
GeneralMy vote of 1 PinmemberImNiranjan20-Jun-10 18:47 
GeneralRe: My vote of 1 PinmemberFrank Kerrigan11-Oct-11 5:05 
GeneralIt's another feedback Pinmembertradakad27-Feb-07 0:00 
GeneralRe: It's another feedback PinmemberFrank Kerrigan13-Apr-07 4:57 
GeneralPopulate database Pinmemberimpu0071-Aug-06 3:19 
GeneralRe: Populate database PinmemberFrank Kerrigan2-Aug-06 10:05 
GeneralThanks for open my eyes! Pinmembersirj9-Sep-05 2:35 
GeneralRe: Thanks for open my eyes! PinmemberFrank Kerrigan9-Sep-05 2:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 12 Nov 2004
Article Copyright 2004 by Frank Kerrigan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid