天天看點

GridView控件的批量删除操作

        1.批量删除

          在進行批量删除時,需要一列選擇框,讓使用者進行選擇删除的條目。是以,在GridView 控件的   <Columns></Columns>标簽對中加入需要進行選擇的選擇框控件。

     <asp:TemplateField HeaderText="删除">

                            <ItemTemplate>

                                <asp:CheckBox ID="del" runat="server" />

                            </ItemTemplate>

                        </asp:TemplateField>

        2.删除前确認

         在這裡使用Button1按鈕進行删除任務,那在進行删除前需要使用者進行最後确認,隻需要在page_load事件中添加如下一行程式:

        Button1.Attributes.Add("onclick", "return confirm(确認要删除選中項嗎?')");

       3.全選記錄按鈕的事件代碼

          當使用者單擊Button2時,如果Text是全選,執行選中所有的行,并設定該按鈕為取消,此時再次單擊Button2,就取消所有選擇。代碼如下

      protected void Button2_Click(object sender, EventArgs e)

      {

          CheckBox cb;

          if (Button2.Text == "全選")

          {

              for (int i = 0; i < GridView1.Rows.Count; i++)

              {

                cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("del");

                  cb.Checked = true;

              }

              Button2.Text = "取消";

          }

          else

          {

              for (int i = 0; i < GridView1.Rows.Count; i++)

              {

                cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("del");

                  cb.Checked = false;

              }

              Button2.Text = "全選";

          }

      }

      其中del是CheckBox的ID值。

    4.删除記錄的按鈕代碼

      protected void Button1_Click(object sender, EventArgs e)

      {

          string sql = "delete from Categories where";

          string cal = "";

          for (int i = 0; i < GridView1.Rows.Count; i++)

          {

              CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("del");

              if (cb.Checked==true)

              {

                  cal += " CategoryID=" + GridView1.DataKeys[i].Value.ToString() + " or";

              }

          }

        if (cal != "")

          {

              sql += cal.Substring(0, cal.Length - 3);

          }

          else

          {

            sql = "";

          }

           objConnection = new OleDbConnection(strConnect);

            cmd = new OleDbCommand(sql, objConnection);

            objConnection.Open();

            int ii= cmd.ExecuteNonQuery();

            objConnection.Close();

            if (ii > 0)

            {

                Response.Write("<script>alert('删除成功!');</script>");

                // 更新GridView控件

                gridViewBind(this.TreeView1.SelectedNode.Value);

            }

       }