2

Possible Duplicate:
What is a NullReferenceException in .NET?

I have two ComboBoxes, one of companies and other of regions (meaning each company has a set o regions) and I want to change the ItemSource of the ComboBox_Region in accordance with the company set at ComboBox_Company.

I have two classes, representing the companies and regions, and a method of region class that returns the list of regions of determined company (passed as parameter).

I have also an event treggered when the ComboBox_Company selected item is changed that should reload the ComboBox_Region source. See below

private void ComboBox_Company_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   Company selected_company= (Company)ComboBox_Company.SelectedValue;
   Dictionary<int, string> regions = Region.GetLookupListByCompanyID(null, selected_company.ID, false);
   ComboBox_Region.ItemsSource = regions.Values;
}

Nevertheless, I got an NullReferenceException error and I don't know how to solve it.

And here goes the XAML code:

<TextBlock Grid.Row="0" Grid.Column="0" Text="{x:Static props:ResourcesWPF.Company}" />
<ComboBox Name="ComboBox_Company" Grid.Row="0" Grid.Column="1" DisplayMemberPath="Name" SelectedItem="ID" Initialized="ComboBox_Company_Initialized"  SelectionChanged="ComboBox_Company_SelectionChanged" />

<TextBlock Grid.Row="1" Grid.Column="0" Text="{x:Static props:ResourcesWPF.Region}" />
<ComboBox Name="ComboBox_Region" Grid.Row="1" Grid.Column="1" DisplayMemberPath="Name" SelectedItem="ID" Initialized="ComboBox_Region_Initialized" SelectionChanged="ComboBox_Region_SelectionChanged" />
Community
  • 1
  • 1
Guilherme Campos
  • 369
  • 7
  • 20

2 Answers2

4

One of the following variables is null

ComboBox_Company
Region
selected_company
selected_company.ID
ComboBox_Region
regions

and maybe the null symbol isn't expected by the method you're passing it to.

You can use the debugger and see. when the exception is thrown, the debugger is normally brought up automatically. at the bottom of the screen, there are 2 small tabs. locals and watch. you can use those to see the values in your variables, and see if one of them is null.

1

You're getting that exception because it's true... You're accessing something that is NULL. In all likelihood, it is selected_company.ID.

Here's some help with your problem:

You're event is firing multiple times, every time your ComboBox's SelectedValue is changing. This includes when the SelectedValue goes from old value to [empty] (before it goes to new value). One way to get around this is to check that you logic is only running when the new value is set. Wrap your logic around an if:

if (e.AddedItems.Count > 0)
{
    //your logic
}

Although, a better way to achieve what you are talking about would be to not use a SelectionChanged event listener but to take advantage of WPF's {Binding} engine. Bind the 2nd ComboBox's ItemsSource to a property of the 1st ComboBox's SelectedItem.

tyriker
  • 2,290
  • 22
  • 31