Is it possible to set the selectedIndex of a combobox based on its value

20.8k views Asked by At

Is it possible to set the selectedIndex of a combobox based on its value, without having to iterate through the datasource?

I set the datasource like this:

caseDBTableAdapters.usersTableAdapter usersAdapter = new caseDBTableAdapters.usersTableAdapter();
            caseDB.usersDataTable users;
            users = usersAdapter.GetUsers();

            cbOwner.DisplayMember = "fullName";
            cbOwner.ValueMember = "userId";
            cbOwner.DataSource = users;

It seems less elegant to have to iterate through the table fx. by doing:

int counter = 0;
            foreach (caseDB.usersRow usersRow in users)
            {

                if (usersRow.userId == selectedUser)
                {

                    cbOwner.SelectedIndex = counter;

                }
                counter++;
            }
2

There are 2 answers

1
Adrian Serafin On BEST ANSWER

Try assing

comboBox.SelectedValue = "value";

or

comboBox.SelectedItem = item;

After question edit:

Set SelectedValue to selectedUser:

cbOwner.SelectedValue = selectedUser;
1
Henk Holterman On

When you use the DisplayMember and ValueMember properties, set SelectedValue.

Otherwise, set SelectedItem.