Reputation: 1749
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
Upvotes: 0
Views: 531
Reputation: 7484
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).
Upvotes: 2
Reputation: 116977
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)
Upvotes: 1