Search This Blog

Wednesday, October 13, 2010

Binding ListBox Control the ADO.NET way.

Note that in this demo, I’m using the Northwind database. Now let’s set up the connection string.

STEP 1: Setting up the Connection string
In your webconfig file set up the connection string there as shown below:
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

Note: DBConnection is the name of the Connection String that we can use as a reference in our codes.

In code behind, you can reference that connection string like this:

private string GetConnectionString()
   return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

STEP 2: Binding the ListBox Control
We can bind the ListBox control the same way as what we did for binding the DropDownList by simply setting its DataTextField and DataValueField.
Now let’s grab a ListBox control from the visual studio toolbox. The mark up should look something like this:
<html xmlns="" >
<head runat="server">
    <title>Binding ListBox</title>
    <form id="form1" runat="server">
       <asp:ListBox ID="ListBox1" runat="server"Height="200px" Width="100px">
And here are the relevant codes for binding the ListBox in the code behind.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)

    private string GetConnectionString()
        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

    private void BindListBox()
        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString());
            string sqlStatement = "SELECT Top(20)* FROM Customers";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            if (dt.Rows.Count > 0)
                ListBox1.DataSource =dt;
                ListBox1.DataTextField = "ContactName"; // the items to be displayed in the list items
                ListBox1.DataValueField = "CustomerID"; // the id of the items displayed
        catch (System.Data.SqlClient.SqlException ex)
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.