简体   繁体   中英

c# Binding values to combobox when editing

I have a windows forms application that has several comboboxes populated with sql database table values.

this is a example of the code for one:

public void brandSelectCB(ComboBox cb)
    {
        string sSQL = " SELECT" +
                      "      id, name" +
                      "  FROM" +
                      "      tbBrand" +
                      "  ORDER BY" +
                      "      name";

        sqlConnect connect = new sqlConnect();
        DataTable dt = new DataTable();
        dt = connect.getBD(sSQL);

        cb.DataSource = dt;
        cb.DisplayMember = "name";
        cb.ValueMember = "id";

My main form has several records like: model, brand, type and when i want to edit a specific recor, I select the record and click the edit button, that enters the values into the corresponding textboxes and comboxes, like this:

private void btnEdit_Click(object sender, EventArgs e)
    {

            this.txtID.Text = lvMain.SelectedItems[0].SubItems[0].Text;
            this.cbBrand.SelectedText = lvMain.SelectedItems[0].SubItems[1].Text;
            this.cbModel.SelectedText = lvMain.SelectedItems[0].SubItems[2].Text;
            this.txtName.Text = lvMain.SelectedItems[0].SubItems[3].Text;
            this.cbType.SelectedText = lvMain.SelectedItems[0].SubItems[4].Text;
    }

works fine, i get the text to the combobox and texboxes, but the values of the comboboxes aren't selected, only the text is. if I chose SelectedValue or SelectedItem I get nothing. I have the corresponding text from the selected item but I have to choose all over again the values from the comboboxes :(

was i clear ? :P

I got it working like this:

int xcb;
xcb = this.cbBrand.FindString(lvMain.SelectedItems[0].SubItems[1].Text);
this.cbBrand.SelectedIndex = xcb;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM