Bohn
Bohn

Reputation: 26919

SelectedIndex causing a crash although it is being set to zero

The code is in a ListBox in a Silverlight application but I think the issue is not really specific to that so here is the code:

    MyListBox processListBox = (sender as MyListBox);
    if (processListBox != null)
    {
        if (processListBox.SelectedItem == null)
            processListBox.SelectedIndex = 0;
    }

so it is crashing on

processListBox.SelectedIndex = 0;

with an IndexOutOfRange exception and the weird thing is that when I hover over the SelectedIndex it is showing -1 so let's say for some crazy reason the value is -1 but still we are setting it to zero so why it still crashes?

Upvotes: 0

Views: 464

Answers (1)

JimiLoe
JimiLoe

Reputation: 978

Maybe it's that simple? If your ListBox contains no items, then setting

processListBox.SelectedIndex = 0;

will throw an IndexOutOfRange exception because there is nothing to select...

Upvotes: 2

Related Questions