萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> asp.net編程 >> GridView實現全選及刪除源代碼

GridView實現全選及刪除源代碼

前台代碼
<asp:templatefield headertext="選擇"> <itemtemplate></itemtemplate><asp:checkbox id="CheckBox2" runat="server"></asp:checkbox></asp:templatefield><asp:button id="Button1" onclick="Button1_Click" runat="server" text="全部選中"></asp:button><asp:button id="Button2" onclick="Button2_Click" runat="server" text="刪除所選"></asp:button>

後台代碼
protected void Button1_Click(object sender, EventArgs e) { if (Button1.Text == "全部選中") { foreach (GridViewRow row in GridView1.Rows) { CheckBox CheckBox2 = (CheckBox)row.Cells[0].FindControl("CheckBox2"); CheckBox2.Checked = true; } Button1.Text = "全部不選"; } else { foreach (GridViewRow row in GridView1.Rows) { CheckBox CheckBox2 = (CheckBox)row.Cells[0].FindControl("CheckBox2"); CheckBox2.Checked = false; } Button1.Text = "全部選中"; } } protected void Button2_Click(object sender, EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { CheckBox CheckBox2 = (CheckBox)row.Cells[0].FindControl("CheckBox2"); if (CheckBox2.Checked == true) { SqlConnection conn = Fun.InitConn(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "delete from Comment where Comment_ID=’" + row.Cells[2].Text + "’ "; conn.Open(); comm.ExecuteNonQuery(); conn.Close(); } } } 

 

copyright © 萬盛學電腦網 all rights reserved