TIP OF THE DAY : Override the tag in a webcontrol

For my New Years Resolution, I'm going to try and start blogging more both here and on my company blog. As a result, I'll most likely revert to these small babies -- Tip of the Day. Hopefully these posts can be short and sweet.

 

Here's the background on this one. I was writing a control that I needed to be the focus of a particular page. I really didn't like how the default base tag of the WebControl class (to write your own control in the assembly rather than use a UserControl) was a SPAN. I really wanted it to be a div. Turns out there is a property you can override in the WebControl class called TagKey.

 

Here's how you can override it for a div.

   1:  //C#
   2:   
   3:  protected override System.Web.UI.HtmlTextWriterTag TagKey{
   4:          get { return HtmlTextWriterTag.Div; }
   5:  }

   1:  'VB
   2:   
   3:  Protected Overloads Overrides ReadOnly Property TagKey() As System.Web.UI.HtmlTextWriterTag
   4:    Get
   5:      Return HtmlTextWriterTag.Div
   6:    End Get
   7:  End Property

The property type is of type System.Web.UI.HtmlTextWriterTag. So you can do other tags beside div and span. You can check that property out on this MSDN doc page.



kick it on DotNetKicks.com

3 Comments

  • You can override it as you are doing, since it's only a property getter and not settable. However, normally what you would do to set Tagkey, is, via one of the WebControls constructor overloads. One of those overloads takes a tagkey. What i do normally is :

    public class MyWebControl : WebControl
    {
    public MyWebControl()
    : base(HtmlTextWriterTag.Div)
    {
    }
    }

  • It's really the same thing... yours just uses the constructor to do the lifting other than OO inheritance. Either way... it works.

  • Actually I was looking for a way to do this the other day... Easier than I thought1

Comments have been disabled for this content.