欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

gridview中实现radiobutton的单选示例

程序员文章站 2024-02-28 15:40:22
c# 代码 复制代码 代码如下: protected void gridview1_rowdatabound(object sender, gridviewrowevent...
c# 代码
复制代码 代码如下:

protected void gridview1_rowdatabound(object sender, gridviewroweventargs e)
{
if (e.row.rowtype == datacontrolrowtype.datarow)
{
radiobutton rb = (radiobutton)e.row.findcontrol("rbtselect");
if (rb != null)
rb.attributes.add("onclick", "onclientclick('" + rb.clientid + "','" + e.row.rowindex + "')"); //把选中行的rowindex也传过去,提交后在服务器端取值时用
}
}

javascript代码
复制代码 代码如下:

<script type="text/javascript">
function onclientclick(selectedid, rowindex)
{
//用隐藏控件记录下选中的行号
var hidden = document.getelementbyid("hidden1").value=rowindex;

var inputs = document.getelementbyid("<%=gridview1.clientid%>").getelementsbytagname("input");
for(var i=0; i <inputs.length; i++)
{
if(inputs[i].type=="radio")
{
if(inputs[i].id==selectedid)
inputs[i].checked = true;
else
inputs[i].checked = false;

}
}
}
</script>

hmtl代码:
复制代码 代码如下:

<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false"
width="648px" font-size="9pt" onrowcommand="gridview1_rowcommand"
datakeynames="id" onrowdatabound="gridview1_rowdatabound">
<columns>
<asp:templatefield>
<itemtemplate>
<asp:radiobutton id="rbtselect" runat="server" />
</itemtemplate>
</asp:templatefield>
<asp:templatefield headertext="文件名">
<itemtemplate>
<asp:linkbutton runat="server" id="lbtdirname" commandname="change" commandargument='<%#container.dataitemindex %>'>
<%#eval("aa") %>
</asp:linkbutton>
</itemtemplate>
</asp:templatefield>
<asp:boundfield datafield="bb" headertext="字段1" />
<asp:boundfield datafield="cc" headertext="字段2" />
<asp:boundfield datafield="dd" headertext="字段3" />
<asp:boundfield datafield="ee" headertext="字段4" />
</columns>
</asp:gridview>

<input id="hidden1" type="hidden" runat="server"/>