Agha Usman

Lives in Karachi (Pakistan) and work for Ciber Strategies

April 2009 - Posts

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.  
Get Repeater Control Output in String

In this post I will share with you a small code snippet which will help you to get the repeater control output in string variable.

   1: Dim sb As New StringBuilder()
   2: Dim objHtml As New HtmlTextWriter(New System.IO.StringWriter(sb))
   3:  
   4: If dt.Rows.Count > 0 Then
   5:     Repeater1.DataSource = dt
   6:     Repeater1.DataBind()
   7: End If
   8:  
   9: Repeater1.RenderControl(objHtml)
  10: Return sb.ToString() 

 

Well, I have used a little trick here. The RenderControl method of repeater control can put all the HTML in HtmlTextWriter Object and from HtmlTextWriter Object we have simply dump the output the to the string builder. That’s it ….

Posted: Apr 13 2009, 09:30 PM by aghausman12 | with 1 comment(s)
Filed under: ,
More Posts