在DataGrid或DataList等容器上面实现RadioButton的单选功能

今天遇到个问题 在DataGrid里做一个RadionButton控件想实现单选的功能,可是却无法进行RadioButton的单选, 原因是因为DataGrid的模版列会自动为每个空间起个新名字, 而在DataGrid显示后, 这些RadioButton的名字是不相同的, 包括其GroupName也不同, 而客户端的<input type="radio">恰恰是通过name属性来分组的, 这样就没有办法在DataGrid中实现RadioButton的单选, 而是每个都可以选, 变成CheckBox了。


网上查了资料 具体解决办法如下 (转自http://www.cnblogs.com/Monday/archive/2006/11/29/576950.aspx

下面已DataGrid为例子,在模板列上加一个RadioButton:radio1
<ItemTemplate>
   <asp:RadioButton id="radio1"  onclick="javascript:CancelSelect(this,'myDataGrid');" runat="server"></asp:RadioButton>
  </ItemTemplate>

myDataGrid即为DataGrid的名称,目的是为了如果页面上还有别的RadioButton,可以互不影响,单选myDataGrid中的RadioButton只对本容器中的RadioButton有影响。

Javascript脚本为

<script language="javascript">
 function CancelSelect(obj,tempSpan)
 {
 elem=obj.form.elements; 
 var strTemp = tempSpan;
 for(i=0;i<elem.length;i++)
 {
  if (elem[i].type=="radio" && elem[i].id != obj.id && obj.name.substr(0,elem[i].name.indexOf(':')) == strTemp)
  {
   elem[i].checked = false;
  }
 }
 }  
</script>

原文地址:https://www.cnblogs.com/conquer/p/1227905.html