Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Change the render behavior of my custom control from being a span

When writing a custom control it always rendered as an HTML span element. How can I change it for example to a div?

like image 471
Kasrak Avatar asked Jul 05 '09 15:07

Kasrak


2 Answers

Derive your control from WebControl as follows:

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

That is, use the base class constructor that accepts the tag to use.

like image 170
John Saunders Avatar answered Sep 27 '22 20:09

John Saunders


If you derive from CompositeControl there is no constructor that takes a tag type. You can override TagKey (I haven't tried it), but a more flexible option is to override the RenderBeginTag method and make it do what you want. The base class renders a "span" opening element, but you don't have to call the base class method. You don't have to call anything if you don't want anything rendered (in which case also override RenderEndTag and don't call anything there either). For example,

public override void RenderBeginTag(HtmlTextWriter writer)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Class, "reportViewer");
        writer.AddAttribute(HtmlTextWriterAttribute.Id, "QueryViewerWrapper");
        writer.RenderBeginTag(HtmlTextWriterTag.Div); 
    }

This code produces

<div class="reportViewer" id="QueryViewerWrapper">

which is exactly what I needed for this particular composite control of mine, a div with a class to wrap a ReportViewer control. I include the ID just to make the output easier to spot.

like image 25
mcb2k3 Avatar answered Sep 27 '22 21:09

mcb2k3