【问题标题】:Delete multiple rows in a DataGridView(table)删除 DataGridView(table) 中的多行
【发布时间】:2012-06-21 20:53:10
【问题描述】:

我有一个可数据的“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);
        }
    }

【问题讨论】:

  • 你有异常吗?我的猜测是,当您在集合更改时删除第一行时,foreach 应该会产生异常。
  • 一点也不例外。好像没有循环foreach,
  • 尝试将其从 foreach 循环中移除:myTable.Rows.Remove(dataRow);
  • 我不这么认为,它只会删除一行并且可能会出现异常,因为 dataRow 是在 foreach 循环中定义的。
  • 哦,对不起,复制粘贴错误,我想到了这一行:dgv.DataSource = myTable;

标签: c# winforms datagridview


【解决方案1】:

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

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);
            } 

【讨论】:

  • 您选择了该行,但您是否删除了它?我看到你评论了删除行。
  • @LoveThanks...忘了我评论了这些。
【解决方案2】:

看起来您只是从 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);
    }
}

【讨论】:

  • 那么如何从表中删除行并再次与网格绑定呢?好地方在哪里?
  • 你的表格已经绑定到gridview,不需要重新绑定。只需从 DataTable 中删除 DataRows。
  • 我的意思是你有一个要删除的列表,如何将它应用到我的表中?
  • toDelete 列表包含 DataTable 中的所有“已检查”行。从列表中删除选中的 DataRows 后,它们就会从 GridView 中删除,因为它已绑定到 DataTable。它可能不是最优雅的解决方案,但我相信它有效。
  • 但是如何删除 toDelete 中的行。你的意思是 foreach(DataRow dr in myTable.Rows) { if (toDelete.Contains(dr)) myTable.Rows.Remove(dr);}
【解决方案3】:

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

引起的
 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()); 

感谢大家的帮助。

【讨论】:

    【解决方案4】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      相关资源
      最近更新 更多