Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object reference not set to instance of an object when passing object to new window

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading