views:

230

answers:

2

I have a created a UserControl with a combobox in it. This combobox is populated from a xml, when this is not present, it is loaded from resource file.
It works fine in the program, but it can't be displayed in designer - it says: "Object reference not set to an instance of an object."

In the class responsible for loading the list from xml the null reference check is skipped for reasons beyond my understanding...

public SortedDictionary<string, string> Countries
{
    get
    {
        if (object.ReferenceEquals(countries, null))
        {
            GetCountryList();
        }
        return countries;
    }
}

Populating of the comboBox goes like this:

comboBoxCountry.DataSource = new BindingSource(Program.language.Countries, null);

Program.language is initialized in Program, but it does not help for the Designer.

The question is, how (when, at what event) should I populate the ComboBox (=load list from xml) to be able to display my control in designer.

+3  A: 

If possible, you want to check for this.DesignMode and then simply not load the ComboBox at design-time.

jasonh
This seems to be working. Is there any reason, why <code>if(!this.DesignMode</code> does not work in component's constructor, while it does work in Load event?
Lukas
When you say it doesn't work, what happens?
jasonh
It seems to be ignored... This does not work - it cannot be displayed in designer. public LoacationUserControl() { InitializeComponent(); if (!this.DesignMode) { LoadCountries(); } } This does work: private void LoacationUserControl_Load(object sender, EventArgs e) { if (!this.DesignMode) { LoadCountries(); } } In both cases the LoadCountries() content is in if (!this.DesignMode){}
Lukas
A: 

Does GetCountryList() set a member variable? If so, move that call to a method. Property get accessors and the ToString() method are assumed pure: the program state before and after must be identical. Violating this assumption can cause all sorts of problems, especially designer/debugger/runtime inconsistency. Various rants have taken place, but the best thing to do is understand the assumption, follow it, and let it work to your advantage as you debug.

280Z28
Yes, it does initialize one. It basically means, that before getting the Property I'll have to manualy call a method filling the list and by that providing any data needed by the property. Am I right?
Lukas