I have a web user control that holds three dropdownlists: One holds days, second holds months and the third one holds years. Days and months are static.But year items will change upon need to avoid entering wrong year. Let me first list here what I do in order, then i’ll ask my question:
- I have a private int yearSpan.
-
In private method PopulateYearList I say:
int year = DateTime.Now.Year; int span = year - this.yearSpan; for (int i = span; i <= year; i++) { ddlYears.Items.Add(i.ToString());//Here I get NullReferenceException } -
I’ve overriden the default constructor to receive
yearSpanas an argument:public DatePicker(int yearSpan) { this.yearSpan = yearSpan; this.PopulateYearList(); }
Now, as you might have guessed in my PopulateYearList method I get NullReferenceException because I try to add an item to ddlYears that has not been constructed yet. What would you suggest to do to solve this?
Ether call the
PopulateYearListin thePage_Loadof yourusercontrol. Like this:Or make the
PopulateYearListpublicand call it on thepagewhen you bind thepagecontrols