65.9K
CodeProject 正在变化。 阅读更多。
Home

增强的 RadioButtonList Web 控件

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.50/5 (6投票s)

2006年8月10日

viewsIcon

45693

downloadIcon

236

本文档描述了如何增强 .NET 的 RadioButtonList Web 控件,使其在每个单选按钮前,文本能够很好地换行显示。

引言

如果您使用 .NET RadioButtonList Web 控件,您可能知道它存在左边距(换行)问题(见下图左侧)。本文将提供源代码,创建一个继承自 RadioButtonList 控件的 Web 自定义控件,以解决此问题。

Sample image

以下是源代码。您可以复制下面的代码,也可以下载本文顶部的源代码文件。

使用此 Web 控件时,唯一发生的事情是,当 radiobuttonlist 渲染到页面时,JavaScript 会将单选按钮及其关联的文本拆分为两个 <td> 标签,而不是一个。

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);
}
}
}
 
© . All rights reserved.