Why am I getting an "IndexOutOfRangeException was unhandled" here?

174 views Asked by At

comboBoxWeekToSchedule has 13 entries in it when I select the one at index 3 (the fourth item in comboBoxWeekToSchedule). Yet a "IndexOutOfRangeException was unhandled" exception is thrown.

Here is the code that runs which is throwing the exception (on the first line of the handler):

private void comboBoxWeekToSchedule_SelectedIndexChanged(object sender, EventArgs eargs)
{
    DateTime dt = Convert.ToDateTime(comboBoxWeekToSchedule.ValueMember[comboBoxWeekToSchedule.SelectedIndex]);
    DisableICRVBS(AYttFMConstsAndUtils.IsFirstWeekOfMonth(dt));            
}

The values in comboBoxWeekToSchedule are dates in LongDateString format; the one in particular I chose is "Monday, March 7, 2016"

So how is it that SelectedIndex could possibly be out of range?

1

There are 1 answers

2
Jens Meinecke On BEST ANSWER

ValueMember is a string. It is used by the ComboBox control to retrieve (using reflection) the value that is associated with a particular element when you use the comboBoxWeetToSchedule.SelectedValue property. So you might set it something like "Date" and when you reference SelectedValue you will really be retrieving the SelectedItem's Date property.

Doing an index on that string will retrieve the 'nth' character which I am sure is not what you want to do. Since you have not provided any code that sets ValueMember, I can only assume that you are setting it to a string of 3 characters or less, which is why it is falling over.

What you really want to do in your code is retrieve the value instead:

DateTime dt = Convert.ToDateTime(comboBoxWeekToSchedule.SelectedValue);