Anas Tasadduq

Anas Tasadduq

  • 1.8k
  • 3
  • 7k

Fill data in ComboBox from DataTable using Access database

Jul 5 2014 9:58 AM
I have a two column table in an MS Access database and want to fill its second column in a ComboBox from where the user can make a selection. I'm using a DataTable to do it. The code is below:
 
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection connect = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Anas\Dropbox\C# Projects\2.Database\ClOsODb.accdb; Persist Security Info=False");
connect.Open();
OleDbCommand cmd = new OleDbCommand("select * from Course Number and Name", connect);
OleDbDataReader odr = null;
odr = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(odr);
course_Number_and_NameComboBox.DataSource = table;
course_Number_and_NameComboBox.BindingContext = this.BindingContext;
course_Number_and_NameComboBox.DisplayMember = "Course Number and Name";
course_Number_and_NameComboBox.ValueMember = "ID";
connect.Close();
}
 
 However, the problem is that when I run the application, the ComboBox is empty! It doesn't get filled. Can anyone help me and tell me where I am wrong and what should I do? Help will be greatly appreciated.
 
Also, can anyone tell me how will I get the value in the first column of the selected row of the DataTable when a selection is made at the ComboBox(in other words, when an item will be selected in the ComboBox-second column of a row in the table-how will I know which row is selected in the ComboBox and how will I get the value in the first column of the same row)? 

Answers (3)