复选框全选、批量删除
// 脚本全选
1 <head runat="server"> 2 <title></title> 3 <script type="text/javascript"> 4 function selectAll(chk) { 5 var checkboxs = document.getElementsByTagName("input"); 6 for (var i = 0; i < checkboxs.length; i++) { 7 if(checkboxs[i].type == "checkbox"){ 8 checkboxs[i].checked = chk.checked; 9 } 10 } 11 } 12 </script> 13 </head>
1 <HeaderTemplate> 2 <asp:CheckBox ID="cboSelectAll" Text="全选" runat="server" AutoPostBack="True" oncheckedchanged="cboSelectAll_CheckedChanged" />| 4 <input type="checkbox" id="htmlCboSelectAll" onclick="selectAll(this)" />JS全选 <br /> 6 <asp:LinkButton ID="lbDeleteSelected" runat="server" 7 onclick="lbDeleteSelected_Click" OnClientClick="return confirm('确定要批量删除吗?')">批量删除</asp:LinkButton> 8 </HeaderTemplate>
1 //批量删除 2 protected void lbDeleteSelected_Click(object sender, EventArgs e) 3 { 4 bool hasDeleteRow = false;//是否有选中要删除的项 5 StringBuilder bookIDs = new StringBuilder("delete from BookInfo where bookid in("); 6 //遍历GridView中的行,获取被选中行的主键值 7 foreach (GridViewRow row in this.gvBookInfos.Rows) 8 { 9 if (((CheckBox)row.FindControl("cboSelect")).Checked) 10 { 11 hasDeleteRow = true; 12 int bookID = Convert.ToInt32(this.gvBookInfos.DataKeys[row.RowIndex].Value); 13 bookIDs.Append(bookID+","); 14 } 15 } 16 //没有选中行时,给出相应提示 17 if (!hasDeleteRow) 18 { 19 Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('请选择要删除的选项!')", true); 20 return; 21 } 22 string ids = bookIDs.ToString(); 23 ids = ids.Substring(0,ids.Length-1)+")"; 24 int result = DBUtil.ExecuteSql(ids); 25 if (result > 0) 26 { 27 Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('批量删除成功!')", true); 28 GridViewBind(); 29 } 30 else 31 { 32 Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('批量删除失败!')", true); 33 } 34 }
// 复选框全选状态
1 protected void cboSelectAll_CheckedChanged(object sender, EventArgs e) 2 { 3 //先获取到全选复选框的状态 4 bool state = ((CheckBox)this.gvBookInfos.HeaderRow.FindControl("cboSelectAll")).Checked; 5 //再设置每一个项中的复选框状态 6 foreach (GridViewRow row in this.gvBookInfos.Rows) 7 { 8 ((CheckBox)row.FindControl("cboSelect")).Checked = state; 9 } 10 }