读书人

怎么控制gridview中的checkbox只能有一

发布时间: 2012-01-18 00:23:26 作者: rapoo

如何控制gridview中的checkbox只能有一个被选中??
<asp:GridView ID= "gridShow " runat= "server " Height= "129px " Width= "584px " OnDataBound= "gridShow_DataBound " OnRowDataBound= "gridShow_RowDataBound " AutoGenerateColumns= "False " OnSelectedIndexChanged= "gridShow_SelectedIndexChanged ">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID= "CustomerID " runat= "server " />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField= "CustomerID " HeaderText= "CustomerID " />
<asp:BoundField DataField= "CompanyName " HeaderText= "CompanyName " />
<asp:BoundField DataField= "ContactName " HeaderText= "ContactName " />
<asp:BoundField DataField= "ContactTitle " HeaderText= "ContactTitle " />
<asp:BoundField DataField= "Address " HeaderText= "Address " />
</Columns>

</asp:GridView>

[解决办法]
int j = 0;
for(int i = 0; i < dg.Items.Count; i++)
{
if((dg.Items[i].Cells[0].FindControl( "chkID ") as CheckBox).Checked)
{
j++;
}
if(j > 1)
{
MessageBox.Show(this, "只能选一个! ");
break;
}
}

[解决办法]
我会用jquery来做,纯javascript不会
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<title> 无标题页 </title>
<script type= "text/jscript " language= "javascript " src= "jquery-latest.pack.js "> </script>

<script language= "javascript " type= "text/javascript ">


$(function(){
$( ":checkbox ").click(function(){
$( ":checkbox ").each(function(){
$(this).attr( "checked ", " ");
});
$(this).attr( "checked ", "checked ");
});
});
</script>
</head>
<body>
<input id= "Checkbox1 " type= "checkbox " />
<input id= "Checkbox2 " type= "checkbox " />
<input id= "Checkbox3 " type= "checkbox " />
<input id= "Checkbox5 " type= "checkbox " />
<input id= "Checkbox4 " type= "checkbox " />
</body>
</html>

[解决办法]
在rowdatabound里面给每个checkbox加上onclick属性
<asp:CheckBox ID= "CustomerID " runat= "server " />
((CheckBox)e.Row.FindControl( "CustomerID ")).InputAttributes.Add( "onclick ", "clickcheck(this) ");

js:
function clickcheck(obj)
{
var gridview = document.getElementById( "gridShow ");
var inputs = gridview.getElementsByTagName( "INPUT ");
for(var i=0;i <inputs.length;i++)
{
if(inputs[i].type== "checkbox " && (inputs[i].id != obj.id) && obj.checked)
{
inputs[i].checked = false;
}
}
}

读书人网 >asp.net

热点推荐