Search code examples
c#mysqlwinformscomboboxselectedindex

C# Windows Form set value of selectedIndex comobox


after searching on this site i can't find the correct solution and need help.

I'm trying to modify a field of an user (I simulate that user wants to change their city)

I have a table like this:

+---------+---------------------+
| id_city | name                |
+---------+---------------------+
|       1 | India               |
|       2 | Irland              |
|       3 | France              |
+---------+---------------------+

And when I launch the query and I get the result I need is like that:

+---------+---------------------+
| id_city | name                |
+---------+---------------------+
|       3 | France              |
|       1 | India               |
|       2 | Irland              |
+---------+---------------------+

And in my C# code when initialize the windows forms I fill the combobox:

modifyCityUserComboBox.ValueMember = "id_city";
modifyCityUserComboBox.DisplayMember = "name";
modifyCityUserComboBox.DataSource = dataTable;

Then I try to put in the combobox the city that user have, but in this part I have the problem. When I do:

modifyCityUserComboBox.SelectedIndex = userDto.GetIdCity();

(supose that India is the original city of the user and wants to change it)

I have this error = "Invalid argument= The value of '1' is not valid for 'SelectedIndex. Parameter name= SelectedIndex".

I've been discovered that combobox start selectedIndex in 0 and if I don't order the cities I only need do:

modifyCityUserComboBox.SelectedIndex = userDto.GetIdCity() - 1;

With this "trick" the IdCity it's 0 and combobox accept it but I don't want do it that way. I want show the cities ordered.

I've tried set True the Sort combobox property and not order the cities in the mysql query but I get the same error...

Anyone know how can I do it? Thanks!


Solution

  • use modifyCityUserComboBox.SelectedValue=userDto.GetIdCity();