Question

I'm building my first ASP.net Custom Control and I'm experimenting with the ToolboxDataAttribute that sets the initial markup of the control.

What I've seen so far is that you can't pick any desired tag name for your control, as it should match your control's className for it to work. In this example I have 'MyControl' class and have set a custom TagName using the ToolboxDataAttribute:

[DefaultProperty("Text")]
[ToolboxData("<{0}:MyCustomTagName runat=server></{0}:MyCustomTagName>")]
public class MyControl : WebControl
{
}

When I try to use this custom control on a project, I drag and drop it from my Toolbox and it's rendered as:

<%@ Register assembly="TestCustomControl" namespace="TestCustomControl" tagprefix="cc1" %>
...
<cc1:MyCustomTagName ID="MyCustomTagName1" runat="server"></cc1:MyCustomTagName>

But when I try to run it, the project keeps telling me that: MyCustomTagName is not a known element, and I can't build it.

I've played with it a bit and realized that the control works if I change the TagName to the control's ClassName, so the following works:

<cc1:MyControl ID="MyCustomTagName1" runat="server"></cc1:MyControl>

So my question is:

What is the point of the ToolboxDataAttribute if you can't change the tagName of your control? I can imagine that it could be for adding more markup from the beginning, but then I wonder if I can have the scenario where the TagName does not match the control's ClassName.

I've tried adding the TagName property to the @Register directive, but if I do so, then it asks for the Src property, since this belongs to the User Control syntax and not the Custom Control syntax. Any ideas?

Était-ce utile?

La solution

As you suspect, the primary use of the ToolboxData attribute is to provide additional markup for default values of the control. From MSDN:

To specify initial default values, a control can make use of this attribute. You can use this attribute to customize the initial HTML content that is placed in the designer when the control is dragged from the toolbox onto the form.

For custom controls, only the tag prefix can be customized and is registered to relate to a namespace in an assembly. The control itself is identified by using the class name as tag name. You cannot change this as you can for a user control.

I agree with you that the design of the ToolboxData attribute tempts to try to change the tag name as you specify the complete tag including the tag name - though there is a placeholder for the tag prefix. It would be cleaner if there was also a placeholder for the tag name. This would also avoid errors when you change the class name of a custom control and forget to change the string in the ToolboxData attribute.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top