日期:2014-05-17  浏览次数:20438 次

GridView+CheckBox实现全选反选删除
C# code

如题:
现要求所有操作在服务器端实现
请大家给出详细代码



------解决方案--------------------
控制checkbox用JS:
function checkAll(checked, lstName) {
var input = document.getElementsByTagName("INPUT");
for (var i = 0; i < input.length; i++) {
if (lstName == null) {
input[i].checked = checked;
}
else if (input[i].type == "checkbox" && input[i].id.length > lstName.length && input[i].id.indexOf(lstName) > 0 ) {
input[i].checked = checked;
}
}
}

aspx:
<Columns>
<asp:TemplateField >
<HeaderTemplate >
<asp:CheckBox ID="lstChkAll" runat="server" onclick="checkAll(this.checked)" Text ="全选"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat ="server" ID="cboxTemple" />
</ItemTemplate>
</asp:TemplateField>
</Columns>

删除么,直接用gridview的command事件后台处理
------解决方案--------------------
C# code


protected void cbSelectAll_CheckedChanged(object sender, EventArgs e)
    {
        foreach (GridViewRow gvr in gvList.Rows)
        {
            ((CheckBox)gvr.Cells[0].FindControl("cbSelect")).Checked = ((CheckBox)sender).Checked;
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvr in gvList.Rows)
        {
            if (((CheckBox)gvr.Cells[0].FindControl("cbSelect")).Checked)
            {
                gvList.DeleteRow(gvr.DataItemIndex);
            }
        }
    }

------解决方案--------------------
HTML code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                                      DataKeyNames="KHID" Width="100%" AllowPaging="True" PageSize="20" 
                                      onpageindexchanging="GridView1_PageIndexChanging">
                                      <Columns>
                                          <asp:TemplateField FooterText="全选" HeaderText="选择">
                                                              <HeaderTemplate>
                                                                  <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" 
                                                                      OnCheckedChanged="CheckAll" Text="全选" />
                                                                    
                                                              </HeaderTemplate>
                                                              <ItemTemplate>
                                                                  <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" Font-Names="宋体" 
                                                                      Font-Size="9pt" />
                                                              </ItemTemplate>