I just don't get this...
If I need to dynamically load controls into a web
page I simply need to go PlaceHolder1.Controls.Add(new
Button()); or similar. However when I need to dynamically load a web user
control into a web page then if we use the same syntax it will appear to work
but the web control will throw all sorts of null reference exceptions.
Rather for web user controls you have to use the
syntax
PlaceHolder1.Controls.Add(LoadControl("WebUserControl1.ascx"));
Why is it so! A couple of
questions:
1. Why is there a syntactic difference between
dynamically loading web controls and web user controls???? This trips me up all
of the time and will be a training nightmare for my underlings.
2. Since there is a difference why does the .Add
method not check for a web user control being loaded through the "new"
method rather then the "LoadControl" method and throw and exception if it
is being done the wrong way? (not sure if this is possible but it would really
help.)
3. Has this changed in ASP.NET2?
4. LoadControl requires the path and
filename of the web user control to load. Putting aside that fact
that it is not strongly typed and the fact that the relative location to the web
user control is a problem if the location of web pages changes, etc, etc, etc,
is it possible for a web page or web user control to report their own path and
file name? I have searched but did not find. If this was
possible then we could go
LoadControl(WebUserControl.GetAbsolutePathAndFileName()) which would make for
much more maintanable code.
5. In response to question 4.0, has this at all
changed for ASP.NET2?
Regards
Dave A
protected System.Web.UI.WebControls.PlaceHolder
PlaceHolder1;
private void Page_Load(object sender, System.EventArgs
e)
{
PlaceHolder1.Controls.Add(new
Button());
PlaceHolder1.Controls.Add(new
Label());
PlaceHolder1.Controls.Add(new
DropDownList());
PlaceHolder1.Controls.Add(LoadControl("WebUserControl1.ascx"));
}