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.

Objective/Output:
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>
</asp:Content>

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)
            {
                Conn.Open();
                OleDbCommand cmd = new OleDbCommand("SELECT * FROM Student", Conn);
                OleDbDataAdapter oDA = new OleDbDataAdapter(cmd);
                dt = new DataTable();
                oDA.Fill(dt);
            }

            ListBox1.DataSource = dt;
            ListBox1.DataTextField = "Name";
            ListBox1.DataValueField = "ID";
            ListBox1.DataBind(); 
        }
    }

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
                Conn.Open()
                Dim cmd As New OleDbCommand("SELECT * FROM Student", Conn)
                Dim oDA As New OleDbDataAdapter(cmd)
                dt = New DataTable()
                oDA.Fill(dt)
            End Using

            ListBox1.DataSource = dt
            ListBox1.DataTextField = "Name"
            ListBox1.DataValueField = "ID"
            ListBox1.DataBind()
        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

Posted in .Net, Asp.net, C#, Database, ListBox, MS Access, VB.Net

Leave a Reply

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

     

*