[英]Remove a Datarow from a Datatable
我有一个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);
}
}
}
我认为您不能引用不同于CurrentRow.DataBoundItem
来源的数据表。
您的dt
DataTable是从DataGridView2构造的,而CurrentRow.DataBoundItem
是从DataGridView1构造的。
您必须先在DataGridView1中找到匹配的行,然后才能删除它。
我已经尝试过您的代码,并且可以正常使用:
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”中的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.