views:

167

answers:

2

Hi

I've created a custom control in asp.net, if I drag it onto another web page it works fine, as expected, however I want to use it dynamically as in

   Dim lCustomControl as new cldButton

However I can't work out how to do this, the compiler does not recoginise the cldButton as a control.I will add it to the page latter in the code. I've added the following to the web.config.

<controls>
        <add tagPrefix="cldButton" tagName="cldButton" src ="~/UserControls/customControlButton.ascx"/>

But it seems to make as much differance as my typing is making

Thanks

+1  A: 

Perhaps I'm misunderstanding the question, but if you're talking about creating a control using just code (and not markup), you don't need to add anything to the web.config file.

Simply instantiate a new instance of your control, and add it to the page's Controls collection during Page_Init.

Dim myControl As new cldButton

Page.Controls.Add(myControl)
womp
Sorry didn't make my question exactly clear, that is what I am doing, however the IDE isn't recognising the Dim as new cldButton (I then intend to add it to the Cell, to a TableRow and then the the Table already on the Page) can't understand why
spacemonkeys
I hear what you are saying about not adding it to the web.config, however I added this on advice when the original code (exacly like yours) refused to compile,
spacemonkeys
Is your control in a different project or assembly? Did you add a reference to it?
womp
No the control is created is the same ASP.NET website
spacemonkeys
What's the compile error?
womp
type 'cldButton' is not defined, and yes that is the correct name. I have found that Dim lButton As UserControl = LoadControl("~/UserControls/customControlButton.ascx")Works and allows to add the control to the page, but not access the custom properties .. sigh
spacemonkeys
I didn't realize that you were talking about a custom usercontrol, sorry I was assuming it was a class derived from WebControl. Jeff's answer is what you want.
womp
+2  A: 

You need to use the Page.LoadControl method instead of doing a new to create the custom control. Here's the C# syntax (sorry, I'm not a vb.net guy); it should be easy to convert:

Control customControl = Page.LoadControl("mycustomercontrol.ascx");
customControl.ID = "someID";
ICustomControl customControlType = (ICustomControl) customControl;

I use Web Sites so I have to create an interface for the custom control and manage it that way. If you use web applications, you can cast the customControl right to the type of your control.

And, after you have everything setup, you need to add the control to it's container (I typically use a PlaceHolder control).

Jeff Siver
Superb, was using the LoadControl (see bellow) , but didn't think to cast to an interface ... damn you vb.net. Cheers for your help
spacemonkeys