我的页面中有一个转发器控件.在检查单选按钮时,我需要在所有行(项目模板)中都有一个单选按钮,其余的单选按钮必须取消选中.
这该怎么做?
提前致谢,
托尔
解决方法
不幸的是,在Repeater中使用时,GroupName属性不能按预期工作,这是一个已知错误(
http://support.microsoft.com/kb/316495).问题是Repeater实现了INamingContainer接口,该接口要求所有嵌套控件在呈现为HTML时具有唯一名称.这会导致单选按钮中断,因为为了使它们正常工作,它们必须具有相同的名称.
我遇到过两种解决方法:
1 – 第一个是客户端javascript解决方案.它由Microsoft support提供.或者更容易阅读的版本here.
说明如下.在HEAD中包含以下javascript:
function SetUniqueRadioButton(nameregex,current)
{
re = new RegExp(nameregex);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i]
if (elm.type == 'radio')
{
if (re.test(elm.name))
{
elm.checked = false;
}
}
}
current.checked = true;
}
现在该函数需要链接到转发器的OnDataItemBound事件中的单选按钮.将“RadioButton”替换为RadioButton控件的名称,将“RadioGroup”替换为您选择的GroupName:
protected void Repeater1_ItemDataBound(object sender,RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
RadioButton rb = (RadioButton) e.Item.FindControl("RadioButton");
string script = "SetUniqueRadioButton('Repeater1.*RadioGroup',this)";
rb.Attributes.Add("onclick",script);
}
2 – 第二个解决方案是使用继承自RadioButton的自定义用户控件的服务器端解决方案.教程和源代码可以在这里下载:http://www.codeproject.com/KB/webforms/How_group_RButtons.aspx
