ARTICLE
Displaying Data in a ListBox Web Control
Tags: .NET, Data in ListBox., DataBind, DataBond, DataSet, DataSource, FAQ, ListBox, ListBox Control, OleDbDataAdapter, VB.NET, Web Control
This article decribes how to display 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.
Same well known steps:
1. Create OleDbDataAdapter.
Private
da As OleDbDataAdapter = 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
Private ds As DataSet = 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
Private ListBox1.DataSource = ds.Tables("Employees").DefaultView
Private ListBox1.SelectedIndex = 0
' Set Field Name you want to get data from
Private ListBox1.DataTextField = "FirstName"
' Bind the data
Page.DataBind()
Sample Code: Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) ' Put user code to initialize the page here
' Create an object of OleDbDataAdapter
Dim da As OleDbDataAdapter = 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
Dim ds As DataSet = 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()
End Sub