Sharepoint Forum

Ask Question   UnAnswered
Home » Forum » Sharepoint       RSS Feeds

Custom WebPart: Access Property in User Control Dynamically

  Asked By: Madison    Date: Dec 24    Category: Sharepoint    Views: 4458

I've got a web part that loads a user control in the CreateChildControls
method. I would like to assign a value to a property in my user
control, but I'm having difficulty doing so. Here's the code:

protected override void CreateChildControls()
MyCustomControl x =
Page.LoadControl("~/_controltemplates/Custom/MyCustomControl.ascx") as
x.MyControlProperty = "some value"; //error occurs at this

For some reason I get an "Object Reference not set to an instance of an
object" when I try to assign the value to the property. So how do I
set this value dynamically?



1 Answer Found

Answer #1    Answered By: Alexander Scott     Answered On: Dec 24

The problem is that UserControls loaded inside a web  part don't actually know
what type they are because the ascx  is in one place and the dll in another. So
doesn't know its type and can't access  properties directly. But you can access
them using Reflection. Instead of your code  try the following code snip.

protected override  void CreateChildControls()
UserControl x =
as UserControl;
Type myControlType = x.GetType();
PropertyInfo MyControlProperty =
MyControlProperty.SetValue(x, "some value", null);

I'm assuming that MyControlProperty is a Public string property  in the
codebehind file for your user  control.