1

I have a CheckBox chkAddToGroup which activates this ComboBox cmbGroup. If chkAddToGroup is being checked the following happens:

ObservableCollection<Group> groupColl = new ObservableCollection<Group>() { };
foreach (Group g in GroupHandler.GroupList)
{
    groupColl.Add(g);
}
cmbGroup.ItemsSource = groupColl;
cmbOrganisation.SelectedIndex = 0;
cmbGroup.IsEnabled = true;

As you can see cmbGroup is attached to groupColl (DisplayMemberPath is set in an external Style).

The problem occurs if I try to reset my form. Therefor I have a Button btnReset. If the user clicks on btnReset the application does this:

chkAddToGroup_Unchecked(this, null);

In chkAddToGroup_Unchecked(object sender, RoutedEventArgs e) following happens then:

private void chkAddToGroup_Unchecked(object sender, RoutedEventArgs e)
    {
        cmbGroup.ItemsSource = null;
        cmbGroup.IsEnabled = false;
        cmbGroupRole.ItemsSource = null;
        cmbGroupRole.IsEnabled = false;
    }

As you can see I set ItemsSource = null in order to clear the combobox. (don't know any other way atm)

If the user didn't check the checkbox before hitting the reset button then nothing special happens. But if the user did check the checkbox and selected an item then there is a NullReferenceException as soon as the application tries to execute cmbGroup.ItemsSource = null;

Why does this happen? Any idea?

H.B.
  • 136,471
  • 27
  • 285
  • 357
TorbenJ
  • 4,110
  • 9
  • 41
  • 77
  • Almost all cases of NullReferenceException are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Sep 16 '12 at 20:29
  • Are you sure? cmbGroup.ItemsSource = null; Should not be throwing a NullRefenceExceptoin. – paparazzo Sep 16 '12 at 22:32

2 Answers2

0

I can't assure you this apply to WPF but you can give it a try. It's been long I looked at WPF.

cmbGroup.Items.Clear();

or

for(int i=0; i<cmbGroup.Items.Count; i++)
{
   cmbGroup.RemoveAt(i);
}

or use an empty list

ObservableCollection<Group> emptyList = new ObservableCollection<Group>();
cmbGroup.ItemsSource = emptyList;
codingbiz
  • 25,120
  • 8
  • 53
  • 93
  • 1
    `cmbGroup.Items.Clear();` doesn't work. Haven't tried the other solutions because the problem was another. Anytime the selection of `cmbGroup` changes, an event is fired causing an update to another combobox. The other combobox then reads out the selected items of `cmbGroup` and applies some data of the selected item to itself. But if the selected item == null then nothing can be read out. That was the NullReferenceException :( Anyway thank you for your help! – TorbenJ Sep 17 '12 at 20:00