Good afternoon, help me deal with the problem. There is a combobox:

<ComboBox x:Name="groupNum"SelectionChanged="groupNum_SelectionChanged"> 

There is a listbox:

 <ListBox x:Name="groupSostav" ItemsSource="{Binding}"></ListBox> 

There is an event handler:

 private void groupNum_SelectionChanged(object sender, SelectionChangedEventArgs e) { groupSostav.Items.Clear(); int n = int.Parse(groupNum.Text); for (int i = 0; i < n; i++) { groupSostav.Items.Add(n); } } 

Above in the constructor:

 if (groupNum.SelectedValue == null) { groupNum.Text = "5"; } 

When choosing a value from ComboBox in ListBox, the number of fields should be updated (I chose 9 - it became 9 fields, I chose 5 - it became 5, etc.).

The whole thing starts off normally, 5 fields appear in the ListBox, then I select 4 for example, 5 fields remain, then 3 fields become 4, etc., that is, it takes the previous value, tell me how to make it normal?

  • `ItemsSource =" {Binding} "` - what is this link attached to, some list or what? - Bulson
  • No, nothing is attached - Dmitriy
  • why then is it? remove - Bulson
  • Already, but it did not solve the problem: ( - Dmitry

1 answer 1

 private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { string text = (sender as ComboBox).SelectedItem as string; int n = Int32.Parse(text); listBox.Items.Clear(); for (int i = 0; i < n; i++) { listBox.Items.Add(n); } } 

There are errors at the stage of determining SelectedItem. Here are a few options; check one of them should be working:

 string text = (sender as ComboBox).SelectedItem as string; //string text = (sender as ComboBox).SelectedItem.ToString(); //string text = (e.AddedItems[0] as ComboBoxItem).Content as string; //string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string; 
  • It gives an error: Additional information: The value cannot be undefined. - Dmitriy
  • @ Dmitriy, put yourself in my place ... How can I find out on which line the error occurs? - Bulson
  • here in this string text = (sender as ComboBox) .SelectedItem as string; - Dmitriy
  • @ Dmitriy see which of the options is working, I have one, you may have another. - Bulson