I have tried the following code as well - which yields the same result (i.e. both lblTitle and lblDescription are null)
protected void Page_Load(object sender, EventArgs e)
{
if (_ErrorMessage != null)
{
lblTitle.Text = _ErrorMessage.Message;
lblDescription.Text = _ErrorMessage.Description;
}
}
I had the understanding that the LoadControl function brought the control it is loading up to the current 'state' of the page onto which it is being included on. hence the Init, Page_Load etc are all run as part of the LoadControl call.
Interestingly this (unanswered) asp.net forums post exhibits the same problem as I am experiencing.
MSDN Forums Post
Additionally - From the MSDN:
When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event.
Therefore shouldn't LoadControl correctly initalise the control?
EDIT:
Ok, so I'm answering my own question here ..
I found an answered version of the forum post I linked to above Here
Essentially the answer is that the LoadControl( type, params )
cannot infer the 'page infront' ascx to parse and hence it doesn't bother initalising any of the controls. When you use the LoadControl( "ascx path" )
version it is given the page infront and hence does all the parsing and initalision.
So in summary I need to change the code which is initalising the control and split it into seperate parts. I.e.
Control ErrorCntrl = LoadControl("ErrorDisplay.ascx");
ErrorCntrl.ID = SomeID;
(ErrorCntrl as ErrorDisplay).SetErrorMessage = MessageDetail;
divErrorContainer.Controls.Add(ErrorCntrl);
And it should work ok.. It isn't as neat as my previous attempt, but at least it will work.
I am still open to suggestions to improve the above.
Cheers
Yes, you can use inline code just like in classic asp. You can use 'this' or 'me' to get to the code behind fields, methods, etc.
Best Solution
In the Page_Load of you will have to make a call to Page.DataBind() for
to work.
<%= %> is a shortened response.Write() and is never valid as an attribute, for any server tag.
<%# %> can be used, only if the conatainer is databound (the page in your case).
<%$ %> can be used to access data in resources files.
EDIT: You can also take a look at How to 'bind' Text property of a label in markup which is a smimilar question.