How to Bind MS Access Database Table to ListBox Control ASP.NET C# VB.Net

In my previous articles I have showed how to bind ListBox Control with SQL Server Database. But in this article I will describe how we can Bind MS Access database data into a ListBox control. Since MS Access still a light weight popular database to the customers.

How to Bind MS Access Database Table to ListBox Control ASP.NET Csharp VB.Net

To do Example open MS Access Database and Create below table:

Note: Of course copy your MS Access Database into your application root folder.

Now add a ListBox Control:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>

Now Bind MS Access Data Table to the ListBox Control:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            string sFilePath = Server.MapPath("MSAccess.accdb");
            DataTable dt;
            OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");

            using (Conn)
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM Student", Conn);
                OleDbDataAdapter oDA = new OleDbDataAdapter(cmd);
                dt = new DataTable();

            ListBox1.DataSource = dt;
            ListBox1.DataTextField = "Name";
            ListBox1.DataValueField = "ID";

Note: Don’t forget to add “System.Data” and “System.Data.OleDb” namespaces.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim sFilePath As String = Server.MapPath("MSAccess.accdb")
            Dim dt As DataTable
            Dim Conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sFilePath & ";Persist Security Info=False;")

            Using Conn
                Dim cmd As New OleDbCommand("SELECT * FROM Student", Conn)
                Dim oDA As New OleDbDataAdapter(cmd)
                dt = New DataTable()
            End Using

            ListBox1.DataSource = dt
            ListBox1.DataTextField = "Name"
            ListBox1.DataValueField = "ID"
        End If

    End Sub

Note: Don’t forget to add “System.Data” and “System.Data.OleDb” namespaces.

Hope now you will get your desired output.

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code