c# - 从数据表中删除数据行

标签 c# winforms datagridview

我有一个 Windows 应用程序,我要在其中从数据表中删除一个数据行。 但我有一个异常(exception)。

The given DataRow is not in the current DataRowCollection.

代码:

DataTable dt = new DataTable();
DataRowView currentDataRowView = (DataRowView)DataGridView1.CurrentRow.DataBoundItem;
DataRow row = currentDataRowView.Row;

dt.Rows.Remove(row); // exception here.
DataGridView1.DataSource = dt;

datatable dt的信息如图所示。 datatable dt

我认为我已经将 datarowview 转换为 datarow。

编辑: dt 是从另一个 DataGridView 创建的。

                foreach (DataGridViewRow row in DatGridView2.Rows)
                {
                    DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
                    if (check.Value != null)
                    {
                        if ((bool)check.Value)
                        {
                            //this row has a checkBox set to true (tick is added)
                            //add this row to dataTable ...
                            DataRow myRow = (row.DataBoundItem as DataRowView).Row;
                            DataRow dr = dt.NewRow();
                            dr[0] = myRow[0];
                            dr[1] = myRow[1];
                            dr[2] = myRow[2];
                            dr[3] = myRow[3];
                            if (!dt.Rows.Contains(dr[0]))
                            {
                                dt.Rows.Add(dr);
                            }
                        }
                    }

最佳答案

我认为您不能引用与 CurrentRow.DataBoundItem 来自的 DataTable 不同的 DataTable。

您的 dt DataTable 是从 DataGridView2 构建的,但 CurrentRow.DataBoundItem 来自 DataGridView1。

在删除之前,您必须自己在 DataGridView1 中找到匹配的行。

关于c# - 从数据表中删除数据行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10720204/

相关文章:

c# - 不能声明主体,因为它被标记为抽象

c# - 隐藏 TableLayoutPanel 中两个组合单元格之间的边框

c# - 窗体关闭时如何停止用户控件上的线程

c# - 摆脱 C# datagridview 行中的蓝色背景

c# - DataGridView 单元格的透明选择背景色

c# - DataGridView 是可编辑的,但不会使用 Entity Framework 将更改发送回数据库

c# - 如何通过反射C#获取类中属性的数据类型

c# - 继承其泛型类型的泛型类

c# - 在 WP7 项目中找不到 HttpWebRequest.GetResponse()

具有相同宽度字符的 C# .NET 多行文本框