Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I m working on Data table and need to fill when required, also i need to remove value for sometime if Required if it was filled. Requested you to please provide any method .
So i am getting error
The given DataRow is not in the current DataRowCollection
or
This row already belongs to this table.

What I have tried:

DataTable dt_rptvalues = new DataTable();
dt_rptvalues.Columns.Add("clr_plot_no", typeof(string));

When I need to Insert Value in Datatable

DataRow drow_AllChecked_Records = dt_rptvalues.NewRow();
drow_AllChecked_Records["clr_plot_no"] = NewPlot;
dt_rptvalues.Rows.Add(drow_AllChecked_Records);


And When i need to Remove the Existing Value from Datatable then

DataRow drow_AllChecked_Records = dt_rptvalues.NewRow();
drow_AllChecked_Records["clr_plot_no"] = NewPlot;

foreach (DataRow ddd in dt_rptvalues.Rows)
{
dt_rptvalues.Rows.Remove(drow_AllChecked_Records);
}
Posted
Updated 15-Sep-21 21:57pm

C#
DataRow drow_AllChecked_Records = dt_rptvalues.NewRow(); // create a new row
drow_AllChecked_Records["clr_plot_no"] = NewPlot;        // set a value in one of its columns

foreach (DataRow ddd in dt_rptvalues.Rows)
{
    dt_rptvalues.Rows.Remove(drow_AllChecked_Records);   // try to remove it from the datatable. But it was never inserted there.
} 
 
Share this answer
 
Why are you creating a new row in an attempt to remove it from a DataTable?

Since it';s a new instance of a DataRow, it cannot be part of any existing collection - so the system is right that you cannot remove it!

To add to that, the actual remove code you show looks like it was thrown together without any thought at all: you can't remove any items from a collection inside a foreach loop on that collection - it will immediately throw an exception because the collection has been modified. You don't use the loop variable at all - so you would try to remove the row as many times as there are elements in the collection (if the system didn't throw the two errors above first, which it would).

I'd suggest that you sit down with your course notes and think about your task carefully before you start coding - I don't think from what you have shown us that you have quite grasped the concept of this yet.
 
Share this answer
 
for (int i = dt_rptvalues.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt_rptvalues.Rows[i];
if (dr["clr_plot_no"].ToString() == NewPlot)
{
dr.Delete();
}

}
dt_rptvalues.AcceptChanges();
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900