updatepanel中gridview内的复选框

时间:2014-05-21 11:27:19

标签: c# asp.net gridview updatepanel

我有这个代码,

  <asp:UpdatePanel runat="server">
    <ContentTemplate>   
        <asp:GridView ID="gvTestDetails" runat="server" AutoGenerateColumns="false" OnDataBound="gvTestDetails_DataBound" EnableModelValidation="true">    
            <Columns>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:CheckBox ID="cbSelectRecord" runat="server" AutoPostBack="true"  OnCheckedChanged="cbSelectRecord_CheckedChanged"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

我想要的是,当我检查GridView的Row中的一个CheckBox时,所有其他CheckBox都被取消选中。

3 个答案:

答案 0 :(得分:1)

为什么不使用Ajax Controll Toolkit中的Mutually Exclusive CheckBox

只需将其添加到CheckBox下方:

<ajaxToolkit:MutuallyExclusiveCheckboxExtender runat="server"
    ID="RandomID"
    TargetControlID="cbSelectRecord" 
    Key="AllwaysSameID" />

注意:您需要在项目中包含scriptmanager和AjaxControllToolkit。但这并不坏,因为AjaxControllToolkit提供了很多很棒的东西。

答案 1 :(得分:0)

您可以循环CheckedChanged事件中的所有行,并取消选中所有其他行:

protected void cbSelectRecord_CheckedChanged(object sender, EventArgs e)
{
    CheckBox cb = (CheckBox) sender;
    if(cb.Checked)
    {
        foreach(GridViewRow row in this.gvTestDetails.Rows)
        {
            CheckBox rowRb = (CheckBox) row.FindControl("cbSelectRecord");
            if(rowRb != cb)
              rowCb.Checked = false;
        }
    }
}

答案 2 :(得分:0)

使用JQuery

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
function checkRecAll() {
var len = document.forms['form1'].elements.length;
var fields = document.forms['form1'].elements;
var chkStatus = document.all("GridView1_chkselall").checked
for (i = 0; i < len; i++) {
if ((fields[i].name.indexOf('chkrecords') != -1)||     (fields[i].name.indexOf('chkrecords') != -1)) {
if (chkStatus == true) {
if (document.all(fields[i].name).disabled == false) {
document.all(fields[i].name).checked = true;
}
}
else {
document.all(fields[i].name).checked = false;
}
}
}
}
</script>

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox name="chkselall" ID="chkselall" runat="server" onclick="javascript:checkRecAll()">
                    </asp:CheckBox>Select All
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="chkrecords" runat="server"></asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
             <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Age" HeaderText="Age" />
        </Columns>
    </asp:GridView>