Search code examples
c#winformscomboboxselectedindex

ComboBox SelectValue returns the one before


I have a problem, basically I have a Windows Form application where I create a Theme and a Theme has an Id from an Atelier. This id is selected with a ComboBox that shows the Id of the Atelier from the Atelier table on my database.

Basically I choose an Atelier id with the combobox that is filled like that :

foreach (ListeAteliers listeAt in ListeAteliers.listeAteliers())
{
    cbCreaThemeAt.Items.Add(listeAt.idAt);
}

And then the Theme is created with the SelectedIndex of the Combobox:

try
{
    int iBd = cbCreaThemeAt.SelectedIndex;
    Themes TH;

    if (txbIdThemCrea.Text.Length != 0 && txbNomThemeCrea.Text.Length != 0 && cbCreaThemeAt.SelectedIndex != 0)
    {
        TH = new Themes(txbIdThemCrea.Text, txbNomThemeCrea.Text.ToString(), cbCreaThemeAt.SelectedIndex.ToString());
        monAssoc.LesThemes.Add(TH);
        TH.ajouterTheme(txbIdThemCrea.Text, txbNomThemeCrea.Text, cbCreaThemeAt.SelectedIndex.ToString());
    }
    else
    {
        lblConfirmCreaThemes.Text = "Erreur dans la création";
    }
}
catch (Exception ex)
{
    MessageBox.Show("Erreur dans la création : " + ex.ToString());
}

The problem that I have is that on the app, when I choose an Id with the combobox, when i create my object Theme, the id selected is going to be the one before.

Example : if i have three items : "1","2" and "3" and that I choose "3", the SelectedIndex is going to be "2"

My question is how can I make my SelectedIndex return the exact value I select on the ComboBox and why is it happening?


Solution

  • SelectedIndex returns the 0-based index of the selected item. The first item "1" has index 0 etc. You want to look at the SelectedItem property that will return the actual selected item "3" and not its index which is indeed 2.