Reader Level:
ARTICLE

Displaying data in a ListBox Web Control

Posted by Mahesh Chand Articles | ADO.NET July 06, 2001
Sample example for how to display data in a ListBox Web control.
  • 0
  • 0
  • 45772

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();
}

COMMENT USING

Trending up