ASP.NET Gridview 中使用checkbox刪除的2種方法執行個體分享

來源:互聯網
上載者:User

方法一:
後台代碼: 複製代碼 代碼如下: 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(),"提示","<script>alert('刪除成功!')</script>");
}
}
this.GridView1.DataBind();
}//刪除
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();
}
}

前台代碼:複製代碼 代碼如下:<asp:GridView ID="GridView1" runat="server" DataKeyNames="id">

另外還得添加一列,讓其綁定的欄位為id,並且把這一列的visable屬性設為false
方法二:
後台:複製代碼 代碼如下: 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(),"提示","<script>alert('刪除成功!')</script>");
}
else
{
ClientScript.RegisterStartupScript(GetType(), "提示", "<script>alert('刪除失敗!')</script>");
}
this.DataBind();
}
}
}
}
}
}

前台:複製代碼 代碼如下:<style type="text/css">
.Hidden
{
display:none;
}
</style>
<asp:BoundField DataField="id" HeaderText="編號" >
<HeaderStyle CssClass="Hidden" />
<ItemStyle CssClass="Hidden" />
</asp:BoundField>

新增加一列,這一資料行繫結id欄位,並且visable屬性不能為false,否則取不出值來。

checkbox全選功能:複製代碼 代碼如下:<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)"/>
全選
</HeaderTemplate>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.