1

I'm usually doing web stuff so pardon any ignorance on the topic.

I'm trying to do the Load a combobox from the codebehind like this:

        using (var con = new SqlConnection(ConStr)) {
        try {
            var dt = new DataTable();
            var cmd = new SqlCommand("usp_SelectContactDropDown", con) {                           
            CommandType = CommandType.StoredProcedure };                                      

                var adapter = new SqlDataAdapter {SelectCommand = cmd};
                adapter.Fill(dt);
                ((ComboBox) Controls.Find(ddContact, true)[0]).DataSource = dt;
                ((ComboBox) Controls.Find(ddContact, true)[0]).DisplayMember = "DisplayText";
                ((ComboBox) Controls.Find(ddContact, true)[0]).ValueMember = "ID";
                ((ComboBox) Controls.Find(ddContact, true)[0]).SelectedIndex = -1;
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString()); }
            finally { /* Handle the error*/ }

Where ID is an int. After this I want to set the selected value of the combo box based on the value member. However this seems to be allot trickier then I would think it needs to be. In asp this is pretty straightforward

        ddContact.SelectedValue = o.fk_ContactID.ToString(); 

I've checked out some other questions (Q1,Q2) which seem to be referring to setting the value by the display member. Whats the most elegant way to go about this ? Thankyou in advance.

Community
  • 1
  • 1
bumble_bee_tuna
  • 3,533
  • 7
  • 43
  • 83

1 Answers1

2

You say WinForms, so, unless the combo is in another class, this should work

ddContact.DisplayMember = "DisplayText";
ddContact.ValueMember = "ID";
ddContact.DataSource = dt;
ddContact.Value = Convert.ToInt32(dt.Rows[0]["ID"]);

Also I assume that you have found at least one record from your query

Steve
  • 213,761
  • 22
  • 232
  • 286