我有一个 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的信息如图所示。
我认为我已经将 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/