Free Programming Tutorials & Source Code

 
  • Increase font size
  • Default font size
  • Decrease font size
Home C# Bind an ADO.NET DataTable to a Combobox in C#

Bind an ADO.NET DataTable to a Combobox in C#

E-mail
(1 vote, average: 5.00 out of 5)
Here is a simple code to Bind an ADO.NET DataTable to a ComboBox using C# and Microsoft Access.
Create a MS Access Database, and name it as db.
Add a new table to it:

Table name: Positions
Fields:
ID (number, primary key)
Name (text)

Create a new C# windows project; add a new form to it.
Add a ComboBox to the form, name is as cbPositions.

bindcombobox c#

Switch to View Code mode, copy and paste the following sub:

        void FillComcoBox()
        {
            DataTable dt = new DataTable();
            String strconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Power\\Desktop\\db.mdb";
            OleDbConnection conn;
            OleDbDataAdapter da;
            try
            {
                conn= new OleDbConnection(strconn);
                da= new OleDbDataAdapter("Select * from Positions",conn);
                dt.Clear();
                da.Fill(dt);
                conn.Close();
                this.cbPositions.DataSource =dt;
                this.cbPositions.DisplayMember = "Position";

                this.cbPositions.ValueMember="ID";
            }
            catch ( Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }

You can call this sub in the Form Load Event:

        private void frm_Load(object sender, EventArgs e)
        {
            FillComcoBox();
        }

You may see the Same example in VB.NET, Bind an ADO.NET DataTable to a Combobox in VB.NET

Happy Coding!