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 .


17 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Donna says

    The zip file’s corrupt. Could you email it to me?

  2. Ron says

    Just a note, the extensionless file in the zip is really a compressed file too. Just rename it, or tell it to open with zip/winrar or whatever you use. Youll then find the sln + code

    • srobbins says

      @Ron Thanks for the comment. I’ve just redownloaded and opened it with WinRAR and it looks just fine to me, which is wierd. What are you opening it with?

  3. Stefan Olson says

    WinZip won’t open the file.

    • srobbins says

      I’ve just downloaded WinZIP and opened it just fine, and I’ve also tried it in WinRAR, 7Zip and the built in Windows ZIP folder functionality just fine?

  4. Ryno says

    Thanks a lot for this! It helped me a lot today

  5. Jon says

    I loves reflection… thanks for the post!

  6. John says

    What if i didnt know explicitely what the usercontrol was before runtime.

    Currently i have a dynamically loaded usercontrol and will need to be able to pass parameters to the usercontrol pending on user selected choices preceding the loading of the usercontrol.

    Data.uControl = LoadControl(core.Type.tostring & “.ascx”)
    ….
    Dim par As Control = Me.Parent
    par.Controls.Add(Data.uControl)

    • srobbins says

      There’s not a lot you can do about that John. The only possible solutions I can think of off the top of my head are revert to reflection, have a horrible case statement to construct the relevant type or try and abstract all of the UserControls to a common interface.

  7. Robert W. (Honolulu/Vancouver) says

    Aloha Steven!

    Thank you for excellent solution!! I’ve been searching for 2 days for a way to generically implement User Controls, as well as pass them strongly typed data. I’d first tried introducing an interface. That solved the first part but not the second. Your solution works well with both!

    P.S. I haven’t yet tackled the issue of transferring user entered data from the User Control back to the form but hope to solve this part soon too.

  8. Paul says

    This was a big help. THANKS Steven!

  9. c# code example says

    If you are getting an error then pls change extension code like below,
    //var control = templateControl.LoadControl(controlPath) as UserControl;
    UserControl control = templateControl.LoadControl(controlPath) as UserControl;

  10. keris says

    clever solution
    thnx

  11. Neil says

    Very cool, thanks!

  12. Burr says

    Hi everyone I am developing a data entry form with different questions for different users. how can i dynamicaly add the different questions on page load in vb.net? i’m still learning vb.net.any ideas

  13. Bhavna says

    Thanks for the simple n smart solution.
    It saved me a lot of time…thanks!!



Some HTML is OK

or, reply to this post via trackback.