1
votes

I'm working on a windows phone project. I have a listbox with the following selectionchanged event handler:

private void judgeType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    LoadJudgeCategories(judgeTypeListBox.SelectedItem.ToString());
}

Here is the LoadJudgeCategories method:

void LoadJudgeCategories(string judgeType)
{
    string[] categories = judgeCategories[judgeType];
    List<LabeledTextBox> itemSource = new List<LabeledTextBox>();
    foreach (string cat in categories)
    {
        itemSource.Add(new LabeledTextBox(cat));
    }
    CategoryPanel.ItemsSource = itemSource;
}

judgeCategories is of type

Dictionary<string, string[]>

LabeledTextBox is usercontrol with a textblock and a textbox. CategoryPanel is just a listbox.

Whenever the selected item is changed, I want to clear CategoryPanel, and replace it with a new List.

Occasionally, however, when I change the selection, it gives the exception "value does not fall within the expected range".

How do I fix this?

2

2 Answers

0
votes

This can happen when you add multiple controls with the same name. Try this code. Broken down with newlines for clarity. I turned it into a linq statement, and also named each of the LabeledTextBox something random. Note: the only important thing I did was give the LabeledTextBox a name.

Random r = new Random();
void LoadJudgeCategories(string judgeType)
{
    CategoryPanel.ItemsSource =
        judgeCategories[judgeType]
        .Select(cat => 
            new LabeledTextBox(cat) { Name = r.Next().ToString() }
        ).ToList();
}
0
votes

Just an alternative solution with ObservableCollection - there will be no need to set CategoryPanel.ItemsSource multiple times:

private ObservableCollection<LabeledTextBox> itemSource = new ObservableCollection<LabeledTextBox>();

CategoryPanel.ItemsSource = itemSource; // somewhere in the Constructor

void LoadJudgeCategories(string judgeType) 
{
  itemSource.Clear();
  foreach (string cat in judgeCategories[judgeType])
    itemSource.Add(new LabeledTextBox(cat));
}