Search code examples
c#.netuwpcomboboxoutofrangeexception

(UWP) Indexing List Causes System.ArgumentOutOfRangeException when Accessing ComboBox


I have a problem where indexing a List will break code that is seemingly unrelated to it. Doing anything with the List will cause the exception, but if I just remove the activePeople[] the ComboBox code works. In both cases I have looked through all the Lists and made sure that there are values in all of them, so I don't understand how there can be an OutOfRange exception.

The following code only takes parts from the actual code and doesn't follow the same structure, but both peopleBox and 'activePeople' will be populated before any of the code runs, and SelectionChanged() always runs before RemovePersonClick(). Note peopleBox is binded to ComboBox

class Person 
{
    public string ID;
    public string Name;
}

ObservableCollection<string> peopleBox = new ObservableCollection<string> { "All" }; // More items are added before any of this code runs
List<Person> activePeople = new List<Person>(); // this also get's populated before any of the other code runs

private void RemovePersonClick(object sender, RoutedEventArgs e) 
{
    int selectedPersonIndex = ComboBox.SelectedIndex;

    if(selectedPersonIndex < 1) return; //Don't do anything if "All" or nothing is selected

    activePeople.RemoveAt(selectedPersonIndex - 1); // -1 because it doesn't contain "All" at the start

    //Both of these throw System.ArgumentOutOfRangeException
    //Even though I have verified that the indexes exist
    ComboBox.SelectedIndex = 0; // 0 index always exists as "All" is never removed, i've even tried -1 which should be nothing, but it throws the error
    peopleBox.RemoveAt(selectedPersonIndex);
}

// This code is always run before the RemovePersonClick method
private void SelectionChanged(object sender, SelectionChangedEventArgs e) 
{
    //This causes the issue. If i index activePeople in any way, an error will be thrown in the RemovePersonClick method.
    //Removing this line stops the error. I can't find any link between the two, and I have verified that nothing is out of range.
    string ID = activePeople[0].ID;
}

I have tried removing the activePeople[0] which did solve the issue, but I need to get the value from activePeople. I have checked that values do exist in both the ComboBox and peopleBox, but I still get the error.


Solution

  • // -1 because it doesn't contain "All" at the start

    So if you remove all items, activePeople will become empty, in this situation accessing activePeople[0] is invalid, you should handle this exception like this.

    string ID = activePeople.Count > 0 ? activePeople[0].ID : "All";