本文實例講述了asp.net實現批量刪除功能的方法。對於asp.net的學習有一定的參考價值。分享給大家供大家參考之用。具體實現方法入戲:
.aspx文件代碼如下:
<asp:GridView ID="GridView1" runat="server" Width="100%" EmptyDataText="暫時無數據" BorderColor="White" OnRowDeleting="GridView1_RowDeleting"> <Columns> <asp:TemplateField HeaderText="選擇"> <ItemStyle Width="20px" /> <ItemTemplate> <asp:CheckBox id="id" runat="Server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="id" HeaderText="序號" > <ItemStyle Width="20px" /> </asp:BoundField> <asp:TemplateField HeaderText="標題"> <ItemStyle Width="400px" /> <ItemTemplate> <a href="../shangpu/<%#eval_r("pageurl") %>" target="_blank"><%#eval_r("title") %></a> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="發表時間"> <ItemStyle Width="100px" /> <ItemTemplate> <%# Convert.ToDateTime(eval_r("addtime")).Date.ToString("yyyy-MM-dd") %> </ItemTemplate> </asp:TemplateField> <asp:HyperLinkField DataNavigateUrlFormatString="shangpu_edit.aspx?id={0}" Text="修改" NavigateUrl="shangpu_edit.aspx?id={0}" DataNavigateUrlFields="id" > <ItemStyle Width="30px" /> </asp:HyperLinkField> <asp:CommandField ShowDeleteButton="True" HeaderText="刪除" DeleteText="<div id="de" onclick="JavaScript:return confirm('確定刪除嗎?')">刪除</div>" > <ItemStyle Width="30px" /> </asp:CommandField> </Columns> <EmptyDataTemplate> <font color=red>暫時無數據</font> </EmptyDataTemplate> <RowStyle Height="20px" /> </asp:GridView>
.cs 文件代碼如下:
protected void btndeleteall_Click(object sender, EventArgs e) { string sqltext = "("; for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox chb = (CheckBox)GridView1.Rows[i].FindControl("id"); if (chb.Checked) { sqltext = sqltext + GridView1.DataKeys[i].Value.ToString() + ","; } } sqltext = sqltext.Substring(0, sqltext.Length - 1) + ")"; sqltext = "delete from shangpu where id in" + sqltext; string sqlcon = ConfigurationManager.AppSettings["ConnectionString"].ToString(); SqlConnection con = new SqlConnection(sqlcon); con.Open(); SqlCommand cmd = new SqlCommand(sqltext, con); try { int count = Convert.ToInt32(cmd.ExecuteNonQuery()); if (count > 0) { viewbind(); MessageBox.Show(this, "刪除成功,共刪除" + count + "條記錄!"); } } catch { MessageBox.Show(this, "刪除失敗!"); } finally { con.Close(); con.Dispose(); } }
感興趣的朋友可以調試運行一下本文實例,學有余力的朋友還可以對代碼作出改進以完善其功能。希望本文實例對大家的asp.net學習有一定的幫助作用。