Displaying data in a ListBox Web Control

This simple sample example shows you how to show a column dable in a ListBox control.  I 've used norhtwind.mdb Access 2000 database comes with Office 2000.

ListBox is generally used to display one or multiple columns. In this sample example, I'd show the contents of "FirstName" column of "Employees" table.

Some well known steps:

  1. Create OleDbDataAdapter

    OleDbDataAdapter da = new OleDbDataAdapter( "Select * from Employees", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb");

  2. Create and Fill DataSet

    // Create a DataSet Object
    DataSet ds = new DataSet();
    // Fill DataSet with the data
    da.Fill(ds, "Employees");

  3. Connect DataSet to the ListBox and call Page.DataBond()

    // Set DataSource property of ListBox as DataSet's DefaultView
    ListBox1.DataSource = ds.Tables["Employees"].DefaultView;
    ListBox1.SelectedIndex = 0;
    // Set Field Name you want to get data from
    ListBox1.DataTextField = "FirstName";
    // Bind the data
    Page.DataBind();

Sample Code:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
// Create an object of OleDbDataAdapter
OleDbDataAdapter da = new OleDbDataAdapter( "Select * from Employees", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb");
// Create a DataSet Object
DataSet ds = new DataSet();
// Fill DataSet with the data
da.Fill(ds, "Employees");
// Set DataSource property of ListBox as DataSet's DefaultView
ListBox1.DataSource = ds.Tables["Employees"].DefaultView;
ListBox1.SelectedIndex = 0;
// Set Field Name you want to get data from
ListBox1.DataTextField = "FirstName";
// Bind the data
Page.DataBind();
}


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.