Problem with rendering of the ASP.NET CheckBox control

Damir Dobric Posts

Next talks:



Follow me on Twitter: #ddobric




Few days ago Armin has posted the rendering problem of the ASP.NET 2.0 checkbox control. His problem was to append required custom HTML attributes to any ASP.NET control. This works fine for all controls but not for the checkbox.


The very simple solution presented in this post solves this problem. First I implemented the custom user control, which contains the ASP.NET checkbox control only. Then I overrided the Render() method, which in my case corrects the problem.

Note that the custom checkbox control contains one attribute ‘MyAttributes’ as a place holder for all custom attributes. This is for sure not the most elegant way to append attributes, but the idea is just to show how the problem can be solved.


Here is the full code:



<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CheckBoxControl.ascx.cs" Inherits="CheckBoxControl" %>

 <asp:CheckBox ID="CheckBox1" runat="server" />



using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.IO;


public partial class CheckBoxControl : System.Web.UI.UserControl


    protected void Page_Load(object sender, EventArgs e)





    private string m_Attributes;

    public string MyAttributes




            return m_Attributes;




            m_Attributes = value;




    protected override void Render(HtmlTextWriter writer)


        string rendered = RenderToString(CheckBox1);


        rendered = rendered.Replace("/>", m_Attributes + "/>");






    protected string RenderToString(WebControl ctrl)


        StringBuilder stringBuilder = new StringBuilder();

        StringWriter stringWriter = new StringWriter(stringBuilder);

        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);



        return stringBuilder.ToString();





Custom This file is the Armin’s ASPX page which host additionally the new custom checkbox control.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ComboBoxIssue.aspx.cs" Inherits="ComboBoxIssue" %>


<%@ Register Src="CheckBoxControl.ascx" TagName="CheckBoxControl" TagPrefix="uc1" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">


<html xmlns="" >

<head runat="server">

    <title>Untitled Page</title>



    <form id="form1" runat="server">



          <asp:CheckBox ID="CheckBox1" runat="server" />

          <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>


          <uc1:CheckBoxControl MyAttributes="MyColor='color' MySomething='anything'" ID="CheckBoxControl1" runat="server" />








Posted May 31 2006, 10:33 AM by Damir Dobric
Filed under: is a .Net Community Blog powered by daenet GmbH.