The Scripts Library Community

Bind an ADO.NET DataTable to a ListBox in VB.NET

(1 vote, average: 4.00 out of 5)
  • Category: Visual Basic.NET Snippets
  • Thursday, 25 June 2009 14:44
  • Written by Feras
This example shows how to bind an ADO.NET DataTable to a ListBox in VB.NET and MS Access Database.
First, create a MS Access Database, and name it as db. Add an Employees table to this database:
Table name: Employees
Fields:
ID (number, primary key)
Name (text)

You can modify this Database to fit in your requirements.

Create a new windows project in Visual Studio.NET, and then add a form to this project.
Add a ListBox to the form, name is as lstEmployees.

bind listbox vb.net

Switch to the View Code Mode, and add the BindListBox sub:

    Sub BindListBox()
        Dim pk(0) As DataColumn
        Dim dt As New DataTable
        Dim strconn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Power\Desktop\db.mdb"
        Dim conn As OleDbConnection
        Dim da As OleDbDataAdapter
        Try
            conn = New OleDbConnection(strconn)
            da = New OleDbDataAdapter("Select * from Employees", conn)
            dt.Clear()
            da.Fill(dt)
            pk(0) = dt.Columns("ID")
            dt.PrimaryKey = pk
            conn.Close()
            Me.lstEmployees.DataSource = dt
            Me.lstEmployees.DisplayMember = "Name"
            Me.lstEmployees.ValueMember = "ID"
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

Call this sub from the Form Load Event:

    Private Sub frm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        BindListBox()
    End Sub

That’s it!
Comments
Add New Search RSS
Write comment
Name:
Email:
 
Website:
Title:
 
Please input the anti-spam code that you can read in the image.

!joomlacomment 4.0 Copyright (C) 2009 Compojoom.com . All rights reserved."