-2

I have a subwindow that is supposed to get a string when initialized. The main window has this code:

 CountryView cv = new CountryView(item.Country);
 cv.Show();

item.Country being a string. While the subwindow has:

public partial class CountryView : Window
{
    public CountryView(string thisCountry)
    {
        lblCountryName.Content = $"{thisCountry}";
        InitializeComponent();
    }
}

Label code:

 <Label x:Name="lblCountryName" Content="" VerticalAlignment="Center" HorizontalAlignment="Center"/>

It keeps saying object reference not set to instance of an object. Anyone know what I'm doing wrong?

Jimi
  • 29,621
  • 8
  • 43
  • 61
Orlak333
  • 5
  • 2

1 Answers1

0

The NullReferenceException occurs when you try to access a member of an object that is currently null. In your case, this error is occurring because you're trying to access lblCountryName before the InitializeComponent() method is called, which initializes the elements in your XAML and assigns values to the automatically generated fields in the code behind class.

You should write:

public partial class CountryView : Window
{
    public CountryView(string thisCountry)
    {
        InitializeComponent(); // Initialize the window components first
        lblCountryName.Content = thisCountry; // Set the content after initialization
    }
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
Aqib Chattha
  • 197
  • 11