在Repeater中实现RadioButton单选
引
昨天在项目中尝试在Repeater控件中放置RadioButton,通常情况下,将所有RadioButton的GroupName属性改为一致可以实现单选,然而在Repeater控件中使用同样的方法却失败了。
原因分析
由于RadioButton是服务器控件,放置于Repeater中,生成HTML页面时,会将RadioButton解释为input type=radio,因此每行的GroupName和ID都变得不同了,即使设置了相同的GroupName也无法实现单选。
解决方法
最开始使用了最为简单的办法,直接使用HTML的Input控件,将Type属性设置为Radio
<input type="radio" id="rdb" name="aa"/>
使用这样的方法确实能实现在Repeater中单选,但又涉及到了如何在后台获取HTML控件的问题
一开始在后台是这样写的
HtmlInputRadioButton rdb = item.FindControl("rdb") as HtmlInputRadioButton
需引用命名空间System.Web.UI.HtmlControls
但这样在取值时一直取到的是空值,原因是在前台没加上runat="server",但一旦加上了又会回到了最开始的问题。
于是决定直接在后台在RadioButton的CheckedChanged事件里写方法,代码如下:
RadioButton rdb = sender as RadioButton;
RepeaterItem item = rdb.Parent as RepeaterItem
int count = rptLable.Items.Count;
for (int i = 0; i < count; i++)
{
RadioButton rbLable = rptLable.Items[i].FindControl("rbLable") as RadioButton;
if (i != item.ItemIndex)
{
rbLable.Checked = false;
}
}
使用这样的方法就能既在前台实现单选又在后台获取到控件的值了。
使用后台判断存在的缺点是每次点击后页面会刷新一次