LeugimSnitram LeugimSnitram - 17 days ago 5
C# Question

InvalidArgument=Value '18' is invalid to 'SelectedIndex' Parameter name: SelectedIndex

I have a

Button
where I am able to save data into the database. To do that I will get the information on
Combobox
and on a
Textbox
. I got a collection of items iniside of the
Combobox
and cannot be changed at the moment.

Right now, I have 17 items and every time I save something it will pull to the next item using
cmbID.SelectedIndex += 1;
, but every time I pull to the last item from
Combobox
it will give me an error :


InvalidArgument=Value '18' is invalid to 'SelectedIndex' Parameter name: SelectedIndex


To solve it I've tried to use an if statement:

if (cmbID.SelectedIndex >= 18)
{
cmbID.SelectedIndex = 1;
}


But this is not working, basically if the
Combobox
reach '18' it should go back to the
SelectedIndex
choosen by me.

Do you guys have any idea I can solve this problem?

Answer

You can't have index more than (item count -1) for the combobox, so

if(cmbID.SelectedIndex == (cmbID.Items.Count - 1))
{
    cmbID.SelectedIndex =1;
}else
{
    cmbID.SelectedIndex += 1;
}
Comments