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?
>Solution :
The
Object reference not set to an instance of an object
error occurs when you try to access a member or property of an object that is currently null. In your case, this error is likely occurring because you’re trying to access lblCountryName before the InitializeComponent() method is called, which initializes the controls in your XAML and creates the necessary objects.
You should try:
public partial class CountryView : Window
{
public CountryView(string thisCountry)
{
InitializeComponent(); // Initialize the window components first
lblCountryName.Content = thisCountry; // Set the content after initialization
}
}