Used in ASP. NET Gridview checkbox delete instances of two methods
- 2020-06-15 08:01:04
- OfStack
Method 1:
Background code:
Foreground code:
You also have to add a column bound to id and set the visable attribute of the column to false
Method 2:
Background:
Front desk:
Add 1 column, which is bound to the id field, and the visable attribute cannot be false, otherwise the value will not be retrieved.
checkbox All options:
Background code:
protected void btn_delete_Click(object sender, EventArgs e)
{
for (int i = 0; i <this.GridView1.Rows.Count; i++)
{
int id = Convert.ToInt32(this.GridView1.DataKeys[i].Value);
if ((this.GridView1.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox).Checked == true)
{
Delete(id);
ClientScript.RegisterStartupScript(GetType()," prompt ","<script>alert(' Delete successful! ')</script>");
}
}
this.GridView1.DataBind();
}// delete
private void Delete(int id)
{
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "delete from Notice_Msg where id=@id";
comm.Parameters.Add(new SqlParameter("@id", id));
comm.ExecuteNonQuery();
}
}
Foreground code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id">
You also have to add a column bound to id and set the visable attribute of the column to false
Method 2:
Background:
protected void btn_delete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in this.GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ckb = row.Cells[2].FindControl("CheckBox1") as CheckBox;
if (ckb.Checked)
{
using (SqlConnection sqlCnn = new SqlConnection(str))
{
using (SqlCommand sqlCmm = sqlCnn.CreateCommand())
{
sqlCmm.CommandText = "delete from Regime_Table where id='" + row.Cells[0].Text + "' ";
sqlCnn.Open();
int a= sqlCmm.ExecuteNonQuery();
if (a>0)
{
ClientScript.RegisterStartupScript(GetType()," prompt ","<script>alert(' Delete successful! ')</script>");
}
else
{
ClientScript.RegisterStartupScript(GetType(), " prompt ", "<script>alert(' Delete failed! ')</script>");
}
this.DataBind();
}
}
}
}
}
}
Front desk:
<style type="text/css">
.Hidden
{
display:none;
}
</style>
<asp:BoundField DataField="id" HeaderText=" Serial number " >
<HeaderStyle CssClass="Hidden" />
<ItemStyle CssClass="Hidden" />
</asp:BoundField>
Add 1 column, which is bound to the id field, and the visable attribute cannot be false, otherwise the value will not be retrieved.
checkbox All options:
<script type="text/jscript">
function change(sender) {
var table = document.getElementById("GridView1");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].cells[1].getElementsByTagName("input")[0].checked = sender.checked;
}
}
</script>
<HeaderTemplate>
<input id="Checkbox2" type="checkbox" onclick="change(this)"/>
Future generations
</HeaderTemplate>