解决radiobutton在gridview中无法单选的一种方法

最近在项目中有个单选gridview中某一项的需求,使用radiobutton后发现,虽然最终选择出来的是一项,但是在页面上却可以选择多项,经过查看生成的html代码,发现生成的radio的name属性并不一样,即使已经加了groupname。解决方法代码如下

页面代码:

 <asp:GridView ID="SmartGridView1" runat="server" AutoGenerateColumns="False"
        PageSize="10" AllowPaging="true" DataSourceID="SmartDataSource1" DataKeyNames="DecisionItemID" onrowdatabound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="选择" ItemStyle-Width="5px" ItemStyle-HorizontalAlign="Center">
                <ItemTemplate>
                    <asp:RadioButton runat="server"  GroupName="SelDecision" ID="cbSel" key='<%#Eval("DecisionItemID") %>' />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField DataField="SerialNumber"  HeaderText="决策事项编号" ItemStyle-Width="80px"
                ItemStyle-HorizontalAlign="Center" />
            <asp:BoundField DataField="DecisionMakingMatters" HeaderText="决策事项" ItemStyle-Width="300px"/>
           
    
        </Columns>
    </asp:GridView>

js代码

 1 function onClientClick(selectedId, rowIndex) {
 2             var inputs = document.getElementById("<%=SmartGridView1.ClientID%>").getElementsByTagName("input");
 3             for (var i = 0; i < inputs.length; i++) {
 4                 if (inputs[i].type == "radio") {
 5                     if (inputs[i].id == selectedId)
 6                         inputs[i].checked = true;
 7                     else
 8                         inputs[i].checked = false;
 9                 }
10             }
11         }  

后台代码

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                RadioButton rb = (RadioButton)e.Row.FindControl("cbSel");
                if (rb != null)
                    rb.Attributes.Add("onclick", "onClientClick('" + rb.ClientID + "','" + e.Row.RowIndex + "')");  
            }
        }       

 

posted @ 2016-09-18 12:49  无聊的小剑  阅读(219)  评论(0编辑  收藏  举报