我有一个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的信息如图所示。
我认为我已经将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);
}
}
}
答案 0 :(得分:3)
我认为您不能引用与CurrentRow.DataBoundItem
来自的DataTable不同的DataTable。
您的dt
DataTable是从DataGridView2构建的,但CurrentRow.DataBoundItem
来自DataGridView1。
您必须自己在DataGridView1中找到匹配的行才能删除它。
答案 1 :(得分: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"。