When using an ASP.NET CheckBox (and in out case, inherited from a CheckBox) it renders a span around the checkbox input control, this span control
I spent the last 3 hours pulling my hair to find a solution at this problem.
Here is what came out:
using System.Web.UI;
using System.Web.UI.WebControls;
///
/// Represents a custom checkbox web control.
/// Prevents itself to be wrapped into a tag when disabled.
///
public class CustomCheckBox : CheckBox
{
///
/// Renders the control to the specified HTML writer.
///
/// The HtmlTextWriter object that receives the control content.
protected override void Render(HtmlTextWriter writer)
{
// Use custom writer
writer = new HtmlTextWriterNoSpan(writer);
// Call base class
base.Render(writer);
}
}
Along with the custom control, you'll need a custom HtmlTextWriter:
using System.IO;
using System.Web.UI;
///
/// Represents a custom HtmlTextWriter that displays no span tag.
///
public class HtmlTextWriterNoSpan : HtmlTextWriter
{
///
/// Constructor.
///
/// Text writer.
public HtmlTextWriterNoSpan(TextWriter textWriter)
: base(textWriter)
{ }
///
/// Determines whether the specified markup element will be rendered to the requesting page.
///
/// Name.
/// Tag key.
/// True if the markup element should be rendered, false otherwise.
protected override bool OnTagRender(string name, HtmlTextWriterTag key)
{
// Do not render tags
if (key == HtmlTextWriterTag.Span)
return false;
// Otherwise, call the base class (always true)
return base.OnTagRender(name, key);
}
}
Just FYI, using:
checkbox.InputAttributes.Add("disabled", "disabled");
has the same effect but: