Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same two items in combobox but first one always gets selected C#

I've got really weird problem with combobox on my windows form application.

So my combobox is populated using datasource, it displays names of people and it holds their IDs as cmbRequestor.ValueMember.

public BindingSource requestorBindingSource = null;
private const string cmdAssoc = "SELECT * FROM assoc_vw ORDER BY assoc_name";
requestorBindingSource.DataSource = populateDataTable(cmdAssoc);

cmbRequestor.DisplayMember = "assoc_name";
        cmbRequestor.ValueMember = "ID";
        cmbRequestor.DataSource = requestorBindingSource;
        cmbRequestor.SelectedIndex = 0;

enter image description here

It works fine but if there is an instance of people with the same name and I select 2nd name (of the same name) from the combobox, for some reason once I close the combobox it selects the first name even though I selected 2nd name.

enter image description here

So to make sure they hold different values against their names I have created SelectedIndexChanged event.

private void cmbRequestor_SelectedIndexChanged(object sender, EventArgs e)
    {
        int x = cmbRequestor.SelectedIndex;
        string j = cmbRequestor.SelectedValue.ToString();
        var y = cmbRequestor.Items[x];
    }

When I debug the code and I select 2nd name (of the same name) the ID behind it is 3069. Once I close the combobox and click save to save the form SelectedIndexChanged is triggered again (that should not happen) and it goes to the first person with the same name and its ID is different.

There are no other events on this control and I dont use it anywhere else. It looks like the control gets confused itself if there is an instance of the same name.

like image 726
user1800674 Avatar asked Mar 18 '23 00:03

user1800674


1 Answers

Change DropDownStyle property to DropDownList.
Default value is DropDown and in that case selected item will be determined by the first matched text in the list. DropDown is mainly used in conjunction with autocomplete logics.

EDIT:
If you have to stick with DropDown style, the best workaround will be to handle DropDownClosed event, at that point you will have the correct index selected.

like image 52
E-Bat Avatar answered Apr 25 '23 17:04

E-Bat