1

我有一个 Windows 应用程序,我将在其中从数据表中删除一个数据行。但我有一个例外。

给定的 DataRow 不在当前 DataRowCollection 中。

编码:

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

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

数据表 dt 的信息如图所示。 数据表 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);
                            }
                        }
                    }
4

2 回答 2

3

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

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

您必须自己在 DataGridView1 中找到匹配的行,然后才能将其删除。

于 2012-05-23T12:54:35.373 回答
2

我已经尝试了您的代码,并且没有问题:

        DataTable dt = (DataTable)dataGridView1.DataSource;
        DataRowView currentDataRowView = (DataRowView)dataGridView1.Rows[0].DataBoundItem;
        DataRow row = currentDataRowView.Row;

        dt.Rows.Remove(row); 
        dataGridView1.DataSource = dt;

因此,正如我在上面所写的,错误“给定的 DataRow 不在当前的 DataRowCollection 中”意味着您尝试删除不在 DataTable“dt”中的行。

于 2012-05-23T13:17:40.547 回答