How to pass parameters to the dynamically added user control

In this post, I will explain how you can pass parameter to the dynamically added (from code behind) User Control. Most of you might aware of how we can achieve this in web application project. Following is the code for that

   1: Dim objCon As Control = Page.LoadControl("~/Controls/MyControl.ascx")
   2: Ctype(objCon,MyControl).PropertyOne = "Test"
   3: Ctype(objCon,MyControl).PropertyTwo = "USAM"
   4: MyPanel.Controls.add(objCon)

Now what if you have a web site project which does not have the pre-compiled assemblies and you are no more able to access the class of your user control. That is what the sum of last two ays.

Here is how you can do that by using System.reflection.

   1: Dim objCon As Control = Page.LoadControl("~/Controls/MyControl.ascx")
   2: 'Creating Dynamic Assmebly which holds control
   3: Dim objAssembly As Assembly = Compilation.BuildManager.GetCompiledAssembly("~/Controls/MyControl.ascx")
   4: 'You should definately know the name of your user control class
   5: Dim objType As Type = objAssembly.GetType("Controls_MyControl")
   6:  
   7: 'Properties
   8: Dim objPropOne As PropertyInfo = objType.GetProperty("PropertyOne")
   9: Dim objPropTwo As PropertyInfo = objType.GetProperty("PropertyTwo")
  10:  
  11: 'Setting Value of Properties
  12: bjPropOne.SetValue(objCon, 1, Nothing)
  13: objPropTwo.SetValue(objCon, 13, Nothing)
  14:  
  15: 'Finally placing control on the page
  16: pnlCommentsCon.Controls.Add(objCon)

So in this way you can pass parameters to the dynamically added user control.  
Published Wednesday, April 15, 2009 9:35 PM by aghausman12
Filed under: , ,

Comments

# re: How to pass parameters to the dynamically added user control

Thursday, April 16, 2009 11:25 PM by Neil Chen

Thanks for the good example, I think use VB.net's late binding can achieve the same effect, like this:

Dim obj as Object = CType(objCon, Object)

obj.PropertyOne = 1

obj.PropertyTwo = 2

# re: How to pass parameters to the dynamically added user control

Tuesday, September 15, 2009 5:29 AM by AMIT KUMAR

THANK YOU,

A GREAT PIECE OF CODE INDEED

# re: How to pass parameters to the dynamically added user control

Tuesday, January 05, 2010 5:49 PM by jtaylorbuild1

Who's gonna post the C# version of this?

# re: How to pass parameters to the dynamically added user control

Wednesday, March 30, 2011 12:27 PM by ABdul

Thanks Alot it solve my problem....

Leave a Comment

(required) 
(required) 
(optional)
(required)