Thursday, March 29, 2012

Pass Parameters to Dynamically Loaded Control?

I have a page that dynamically loads a control:

Dim RelatedProductsControlAs Control =LoadControl("~/controls/RelatedProducts.ascx")
RelatedProductsPanel.Controls.Add(RelatedProductsControl)

That works perfectly but the problem is I need to set a Public Property in the control. I know you can pass partameters to the control like this:

LoadControl("~/controls/RelatedProducts.asx", Parameters As Object)

But I am not sure how the create the parameter as an object so that I can pass it? Any help would be greatly appreciated.

Thanks,
Max

Hi,

You can set the public properties of the control as:

Dim RelatedProductsControlAs Control = LoadControl("~/controls/RelatedProducts.ascx")
Ctype(RelatedProductsControl,Relatedproducts) 'here i am casting the control to its class
RelatedProductsControl.PropertyXXX = "something" 'now i can access the properties as i have casted it to the control class
RelatedProductsPanel.Controls.Add(RelatedProductsControl)

Hope this helps,

Vivek


I tried what you suggested and changed my code to this:

Dim RelatedProductsControlAs Control = LoadControl("~/controls/RelatedProducts.ascx")
CType(RelatedProductsControl, RelatedProducts)'here i am casting the control to its class
RelatedProductsControl.PricingEmail =True
RelatedProductsPanel.Controls.Add(RelatedProductsControl)

But I get an error 'Type RelatedProducts in not defined'

Surely I am missing something here?


Dim cAs WebUserControl =CType(LoadControl("~/controls/WebUsercontrol.ascx"), WebUserControl)

c.MySkin ="hj"

Now, this will work only if I can "access" the class WebUsercontrol.vb in my page's page_load. In your case it is giving an error because the control is incontrolsfolder, so unless you add a namespace in your page, or move the control outside of the Controls folder (in the same directory as the page), it will give this error.

HTH,

Vivek


BTW: you can avoid this "type XX not find" issue by creating a <%Register %> tag in your aspx page as:

<%@.RegisterSrc="controls/WebUserControl.ascx"TagName="WebUserControl"TagPrefix="uc1" %>

Just write this tag so that the Page is able to find the UserControl's class (since it is not in the same folder as the page).

But this is an issue when you do not know the name of the control to be created, and AFAIK there is no solution to it because the VS 2005 Website model uses multiple assemblies so using wihthout a common namespace. An alternative is to use Web Application project model (old one followed in VS 2003). You can get the same from:

http://weblogs.asp.net/scottgu/archive/2006/04/05/442032.aspx

Hope this helps,

Vivek


Thank You! Thank You! Thank You!

Your last suggestion worked perfectly and worked with my existing file structure - thanks again!

0 comments:

Post a Comment