Properpies and Controls on a Dynamically Instanciated UserControl

  • Thread starter Thread starter Andrew Robinson
  • Start date Start date
A

Andrew Robinson

I have a user control that I am dynamically loading at run time:

PersonalInformationUserControl pi = new PersonalInformationUserControl();
PlaceHolderPersonalInformation.Controls.Add(pi);

My user control has public properties that in turn access controls on the
UC. I can access the properties, but the subsequent access to the underlying
controls generates a null reference exception. How do I get the control to
build / load all of its content?


pi.DisplayOnly = true; // ok
pi.Email = "(e-mail address removed)"; // null ref on the TextBoxEmail control


within the PI control:


public string Email
{
get { return TextBoxEmail.Text; }
set { TextBoxEmail.Text = value; }
}


Thanks,
 
Hello Andrew,

As for ascx UserControl, it is different from custom webserver control, you
should use the "LoadControl" method(of TemplateControl or Page class) to
create the UserControl instead of simply calling the constructor. For
example:

================
Control control = Page.LoadControl("~/usercontrols/myusercontrol.ascx");

Panel1.Controls.Add(control);
================

Here are some reference articles mentioned this:

#how to dynamically add user controls to pages at runtime using the
LoadControl method.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfSystemWebUITemplateControlClassLoadControlTopic.asp

http://aspalliance.com/565


Hope this helps.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead


This posting is provided "AS IS" with no warranties, and confers no rights.
 
Hi Andrew,

Your properties' accessors need to call one method before accessing
child controls in order to ensure that they have been created.

public string Email
{
get {
EnsureChildControls();
return TextBoxEmail.Text;
}
set {
EnsureChildControls();
TextBoxEmail.Text = value;
}
}

Good luck!

- Matt


----- Original Message -----
From: Andrew Robinson
Date: 8/3/2006 1:22 PM
 
Hi Andrew,

How are you doing on this issue, does my last reply helps you on this issue?

Please let me know if you meet any further problems on this.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead


This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top