Removing SPAN-tags around server control

I had to write some ASP.NET server controls for our current SharePoint portal project. We have very nice DIV-based layout and using standard components that generate table and a lot of JavaScript seems to me like an bad idea. I found out that server controls put container tags around their mark-up. I needed my own tags around output and I found a way how to achieve it.

There are two rendering methods I needed to override: RenderBeginTag and RenderEndTag. Be default these methods create <span> and </span> tag before and after web part outout respectively. When creating web parts DIV-tags are created instead SPANs. Now let’s remove these tags. You need only these two simple overrides:

public override void RenderBeginTag(HtmlTextWriter writer)

public override void RenderEndTag(HtmlTextWriter writer)

That’s it.

Serverless360 Logo

A portal focused on Operations and Support for Microsoft Azure Serverless services


Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    8 thoughts on “Removing SPAN-tags around server control

    • April 9, 2009 at 11:33 pm

      Or override the TagKey property (I forget which property to override if its a non-standard HTML element), and possibly AddAttributesToRender if you need to.

    • September 10, 2009 at 2:39 pm

      You can also inherit from Control instead of WebControl/Composite control to avoid your control rendering surrounding divs or spans.

    • October 30, 2009 at 8:27 pm

      Where do these go?

    • June 16, 2010 at 12:42 pm

      spanx dude – solved my headache :)

    • July 13, 2011 at 5:28 pm

      This saved me some time today, so thank you very much, helpful article.

    • November 10, 2011 at 8:50 pm

      I would like to know where you add these two functions? In the .aspx.cs page or the .aspx page?

    • November 10, 2011 at 10:22 pm

      This code goes to class file of server control.

    • January 26, 2013 at 1:00 am

      An other way to do it:

      public class CustomCheckBox : CheckBox
      protected override void Render(HtmlTextWriter writer)
      // Use custom writer
      writer = new HtmlTextWriterNoSpan(writer);

      // Call base class

      public class HtmlTextWriterNoSpan : HtmlTextWriter
      public HtmlTextWriterNoSpan(TextWriter textWriter)
      : base(textWriter)
      { }

      protected override bool OnTagRender(string name, HtmlTextWriterTag key)
      // Do not render tags
      if (key == HtmlTextWriterTag.Span)
      return false;

      // Otherwise, call the base class (alway true)
      return base.OnTagRender(name, key);

    Leave a Reply

    Your email address will not be published. Required fields are marked *