Reputation: 7124
Getting the good old "Object reference not set to an instance of an object" error. Shortened everything down for the sake of abbreviation:
The .ascx file:
<asp:Label ID="lblcategory" runat="server" Text="Label"></asp:Label>
The .ascx.cs file:
public partial class NewsArticleContainer : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public NewsArticleContainer()
{
lblcategory.Text = "hello there!"; //null reference exception
}
}
Then, I'm putting this User Control into another page after registering it with the web.config file.
The .aspx file:
<MyUC:NewsArticleContainer runat="server"/>
If I put the lblcategory.Text = "hello there!"
line in Page_Load and comment it out of the constructor, it works just fine. However, later, I would like to be able to add instances of this User Control programmatically (i.e. mypanel.Controls.Add(new NewsArticleContainer(x))
, where x is a NewsArticle).
I'm already aware of the requirement to use LoadControl to do this with a User Control --- that's not the problem. The problem is I can't access the web controls in the User Control from the User Control's constructor.
It just occurred to me while writing this: in the case of a User Control, could it be that Page_Load is the equivalent of a constructor in the traditional meaning of creating an instance of a class, and the traditional constructor public ClassName() of a UserControl shouldn't be touched or modified?
Upvotes: 0
Views: 1312
Reputation: 14915
Well you need to understand some thing here. Though UserControl is a class, but control has its own life cycle. The individual control are only available for use once Init of the page life cycle/control life cycle has been called. Before Init, none of your controls are initalised as they do not have unique id's assigned to them. That's why you are getting object reference error. What you could do here is as follwing
public partial class NewsArticleContainer : System.Web.UI.UserControl
{
List<string> NewsArticle = null;
public NewsArticleContainer(List<string> toCreateNewsArticle)
{
NewsArticle = toCreateNewsArticle;
}
protected void Page_Load(object sender, EventArgs e)
{
foreach(string s in NewsArticle)
{
//dynamically create your label control and add it to this user control
Label lb = new Label;
lb.Text = s;
this.Controls.Add(lb);
}
}
}
Pass the input and store the NewsArticle in your class level variable. Then in page load or page_init, dynamically create your label and add to your control
Upvotes: 3