binding COmbo Box to database

Hi,

  I am having trouble populating the Combo Box with the data returned from the Query. Here is my code Can any one please help and tell me what iam doing Wrong:



OleDbCommand myCommand = new OleDbCommand("SELECT Name FROM myTable",myConnection);
myCommand.CommandType = CommandType.Text;



OleDbDataAdapter ad = new OleDbDataAdapter("SELECT Name FROM myTable",myConnection);
DataSet ds = new DataSet();

myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();

ad.Fill(ds);


//myBox.DataSource = ds;
//myBox.DisplayMember = "Name";

myBox.DataSource  = ds.Tables["myTable"];

myBox.DisplayMember = "Name";

myBox.ValueMember = "ID";







Answer this question

binding COmbo Box to database

  • MCUSA

    ok, as the previous writer said it's not necesary to open the connection. But back to your problem. You have this code:
    DataSet ds = new DataSet(); 
    ad.Fill(ds, "myTable"); 
    myBox.DataSource = ds.Tables["myTable"]; 
    myBox.DisplayMember = "Name"; 
    myBox.ValueMember = "ID"; 

    what is worng in it is the binding part. You should have something like:

    myBox.DataSource = ds;
    myBox.DisplayMember = "myTable.Name"; 
    myBox.ValueMember = "myTable.ID"; 

    Best regards,
    Dan

  • cagii

    Hi,
    You don't need to open and close the connection if you're using a dataAdapter.
    Also, your query is missing the ID column.
    So your code would look like this:

    OleDbCommand myCommand = new OleDbCommand("SELECT Name, ID FROM myTable",myConnection);
    OleDbDataAdapter ad = new OleDbDataAdapter(myCommand);
    DataSet ds = new DataSet();
    ad.Fill(ds, "myTable");
    myBox.DataSource  = ds.Tables["myTable"];
    myBox.DisplayMember = "Name";
    myBox.ValueMember = "ID";

    Hope this helps.

  • binding COmbo Box to database