Enhanced RadioButtonList web control






1.50/5 (6 votes)
Aug 10, 2006

45452

221
The article describes how to enhance .NET's RadioButtonList web control to make the text wrap nicely on multiple lines in front of each radiobutton.
Introduction
When you use .NET RadioButtonList web control you properbly know about it's left margin (wrapping) problem (see left picture below). This article will give you the source code to make a Web Custom Control that inherits from the RadioButtonList control to fix this problem.
Here is the source code. You can either copy the code below or download the source file at the top of this article.
The only thing that happens when you use this Web Control, is when the radiobuttonlist has been rendered to the page a javascript will split the radiobutton and it's associated text into into two <td> tags instead of one.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text;
namespace Dfds.MCms.WebControls
{
/// <summary>
/// This control inherit all the features from RadioButtonList.
/// The enhanced feature makes the word wrapping correct, so if the text next to a radiobutton breaks into
/// two lines, then line 2 will not be directly underneath the radiobutton, but an the text is correctly left aligned.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:EnhancedRadioButtonList runat="server"></{0}:EnhancedRadioButtonList>")]
public class EnhancedRadioButtonList : System.Web.UI.WebControls.RadioButtonList
{
private string text;
true),
Category("Appearance"),
DefaultValue("")>
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
protected override void Render(HtmlTextWriter output)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(@"
<script language="'javascript'">
var s;
s = document.getElementById('{0}').outerHTML;
s = s.replace(/<LABEL/gi,'</td><td><LABEL');
s = s.replace(/<td/gi,'<td valign=top');
document.getElementById('{0}').outerHTML = s;
</script>
",this.ClientID);
Page.ClientScript.RegisterStartupScript(this.GetType(), "EnhancedRadioButtonList",sb.ToString());
base.Render(output);
}
}
}