删除DataGridView(表)中的多行

时间:2012-06-19 18:46:17

标签: c# winforms datagridview

我有一个数据“myTable”,它与DataGridView“dgv”绑定。 DataGridView“dgv”有一个复选框列。我的目标是删除按钮事件中检查的行。数据表当然会更新。 现在我的代码只用于删除一行而不是多行。

感谢您的帮助。

 private void btnDel_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgv.RowCount>0)
            {
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
                    if (check.Value != null)
                    {
                        if ((bool)check.Value)
                        {
                            DataRowView currentDataRowView = (DataRowView)dgv.CurrentRow.DataBoundItem;
                            DataRow dataRow = currentDataRowView.Row;

                            int n = dgv.CurrentRow.Index;
                            int intID = Convert.ToInt32(dgv.Rows[n].Cells[0].Value);
                            myTable.Rows.Remove(dataRow);
                            dgv.DataSource = myTable;

                            Int32 intVal = Convert.ToInt32(row.Cells[1].Value);
                            if (intVal == intID)
                            {
                                check.Value = null;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

4 个答案:

答案 0 :(得分:1)

我找到了解决方案。错误是由

引起的
 DataRowView currentDataRowView = (DataRowView)dgv.CurrentRow.DataBoundItem; 

currentDataRowView不是选中的行。 正确的代码是:

                List<DataRow> toDelete = new List<DataRow>(); 
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    {
                        DataGridViewRow row = dgv.Rows[i];
                        DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
                        if (check.Value != null && (bool)check.Value)
                        {
                            DataRow dataRow = (row.DataBoundItem as DataRowView).Row;
                            toDelete.Add(dataRow);
                        }
                    }
                }
                toDelete.ForEach(row => row.Delete()); 

感谢大家的帮助。

答案 1 :(得分:0)

您是否尝试过按索引而不是foreach进行迭代?我认为CurrentRow可能不会每次迭代更新:

try {
                if (dgv.RowCount > 0) {
                    for (int i = 0; i < dgv.Rows.Count;i++ ) {
                        DataGridViewRow row = dgv.Rows[i];
                        DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
                        if (check.Value != null) {
                            if ((bool)check.Value) {
                                dgv.Rows[i].Selected = true;
                                dgv.Rows[i].Cells[0].Selected = true;
                                DataRowView currentDataRowView = (DataRowView)dgv.CurrentRow.DataBoundItem;
                                DataRow dataRow = currentDataRowView.Row;

                                int n = dgv.CurrentRow.Index;
                                int intID = Convert.ToInt32(dgv.Rows[n].Cells[0].Value);
                                myTable.Rows.Remove(dataRow);
                                dgv.DataSource = myTable;

                                Int32 intVal = Convert.ToInt32(row.Cells[1].Value);
                                if (intVal == intID) {
                                    check.Value = null;
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            } 

答案 2 :(得分:0)

看起来您只是从DataGridView中抓取CurrentRow而不是foreach循环中的当前行。您也正在修改正在迭代的集合。这可能有效:

private void btnDel_Click(object sender, EventArgs e)
{
    try
    {
        List<DataRow> toDelete = new List<DataRow>();
        foreach (DataGridViewRow row in dgv.Rows)
        {
            DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
            if (check.Value != null && (bool)check.Value)
              toDelete.Add(((DataRowView)row.DataBoundItem).Row);
        }

        toDelete.ForEach(row => row.Delete());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

答案 3 :(得分:0)

ASPXPAGE:
<strong>Asp.Net : Delete Multiple Records form datagridview in one time<br />
        </strong>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
            CellPadding="4" EnableModelValidation="True" ForeColor="Black">
            <Columns>
                <asp:TemplateField>
                    <EditItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="Sr No" />
                <asp:BoundField DataField="doc_name" HeaderText="Name" />
                <asp:BoundField DataField="doc_add" HeaderText="Address" />
                <asp:BoundField DataField="doc_mob" HeaderText="Mobile No" />
                <asp:BoundField DataField="doc_email" HeaderText="Email" />
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" Font-Size="12pt"
            onclick="Button1_Click1" Text="Delete" />
        <br />



Code Behind Page:
SqlConnection conn = new SqlConnection(@"server=server-pc; database=HMS; integrated security=true");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            load_data();
        }
    }

   public void load_data()
    {
        SqlDataAdapter adp = new SqlDataAdapter("select * from doc_master", conn);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }
   protected void Button1_Click1(object sender, EventArgs e)
   {
       CheckBox ch;
       for (int i = 0; i < GridView1.Rows.Count; i++)
       {
           ch = (CheckBox)GridView1.Rows[i].Cells[0].Controls[1];
           if (ch.Checked == true)
           {
      int id = Convert.ToInt32(GridView1.Rows[i].Cells[1].Text);
      SqlCommand cmd = new SqlCommand("delete from doc_master where ID=" + id + " ", conn);
      conn.Open();
      cmd.ExecuteNonQuery();
      conn.Close();
           }
       }

       load_data();
   }

详细代码访问: http://www.gtuguide.com/2014/05/deleting-multiple-rows-in-gridview.html