Reputation:
I have a windows application in which I am going to delete a datarow from a datatable. But I got an exception.
The given DataRow is not in the current DataRowCollection.
The code:
DataTable dt = new DataTable();
DataRowView currentDataRowView = (DataRowView)DataGridView1.CurrentRow.DataBoundItem;
DataRow row = currentDataRowView.Row;
dt.Rows.Remove(row); // exception here.
DataGridView1.DataSource = dt;
The datatable dt's information as the image shown.
I think that I already have casted datarowview to datarow.
EDIT: dt was created from another 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);
}
}
}
Upvotes: 1
Views: 3537
Reputation: 81610
I don't think you can reference a different DataTable than the one where CurrentRow.DataBoundItem
is coming from.
Your dt
DataTable is being constructed from DataGridView2 but CurrentRow.DataBoundItem
is coming from DataGridView1.
You will have to find the matching row in DataGridView1 yourself before you can delete it.
Upvotes: 3
Reputation: 751
I have tried your code, and it's working with no problem:
DataTable dt = (DataTable)dataGridView1.DataSource;
DataRowView currentDataRowView = (DataRowView)dataGridView1.Rows[0].DataBoundItem;
DataRow row = currentDataRowView.Row;
dt.Rows.Remove(row);
dataGridView1.DataSource = dt;
So as i have wrote above, the error "The given DataRow is not in the current DataRowCollection" means that your trying to delete a row that is not in the DataTable "dt".
Upvotes: 2