Skip to content


Passing Parameters using LoadControl()

Recently I had to put together a SharePoint 2008 Web Part and I wanted to use a User Control for the UI and pass the various Web Part settings into it.  The “standard” way to call LoadControl doesn’t allow us to pass any parameters:

LoadControl

There is an additional overload that takes a Type and a list of parameters but using that doesn’t seem to initialise any of the designer created bits, so referencing any of the sub-controls fails with a null reference exception.

One solution would be to add some public properties to the control, create it using the normal LoadControl, set the properties to the relevant values and display it.  I wasn’t too keen on that approach so instead I created a LoadControl extension method on TemplateControl that provides the following overload:

LoadControlExtension

Extension Method Implementation

The implementation of the extension methoid is very straightforward.  Firstly we take the params we are passed and pull out their types into an array:

Type[] paramTypes = new Type[constructorParams.Length];
for (int paramLoop = 0; paramLoop < constructorParams.Length; paramLoop++)    paramTypes[paramLoop] = constructorParams[paramLoop].GetType();

Once we have the types we can use GetConstructor to lookup the constructor that matches our signature:

var constructor = control.GetType().BaseType.GetConstructor(paramTypes);

Then if our constructor was found, we simply invoke it:

constructor.Invoke(control, constructorParams);

User Control

In our user control code behind we add our required constructor, but we also need to add a default constructor (one with no parameters) or the compiler gets confused and you will get a CS1729 runtime error:

public partial class TestControl : System.Web.UI.UserControl
{    
    public TestControl()    
    {    
    }

    public TestControl(Color color1, Color color2)    
    {       
        Label1.ForeColor = color1;        
        Label2.ForeColor = color2;    
    }
}

And that’s it!  A demo with the extension method class and a sample user control is available here:

LoadControlDemo.zip

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • email
  • Netvibes
  • Ping.fm
  • Print
  • Reddit

Technorati Tags:

Posted in ASP.Net.

Tagged with .