The situation is this. I've got a select query that gets and array of DataRows that I want to insert into a new DataTable.
But when trying to add the Row I get the following error:
"Row already belongs to another Table".
So I tried creating and initializing a new DataRow within the loop(for and foreach loop) then throw an error when initializing the DataRow:
"Inaccessible due to its protection level"
Any Ideas? Feels like I'm missing something silly.
My Code for the first Error:
var DRCurrentAuspragung = _DTAuspragung.Select(#"MerkmalID = "+Convert.ToString(MerkmalID));
_DTCurrentAuspragung = new DataTable();
for (int i = 0; i < DRCurrentAuspragung.Length;i++ )
{
DataRow RowAdd = DRCurrentAuspragung[i];
_DTCurrentAuspragung.Rows.Add(RowAdd);
}
And for the second error:
var DRCurrentAuspragung = _DTAuspragung.Select(#"MerkmalID = "+Convert.ToString(MerkmalID));
_DTCurrentAuspragung = new DataTable();
foreach (DataRow dr in DRCurrentAuspragung)
{
DataRow RowAdd = new DataRow();
RowAdd = dr;
_DTCurrentAuspragung.Rows.Add(RowAdd);
}
Thanks in advance.
The reason of this exception is one DataRow object cannot belong to more than one table. One solution, is to create a copy of this row with the help of the ImportRow method:
_DTCurrentAuspragung.ImportRow(RowAdd);
And don't forget to use Clone() after selecting rows, beacause both of these tables must have the same structure:
DataTable _DTCurrentAuspragung = _DTAuspragung.Clone();
So, the result is:
var DRCurrentAuspragung = _DTAuspragung.Select(#"MerkmalID = " + Convert.ToString(MerkmalID));
_DTCurrentAuspragung = _DTAuspragung.Clone();
for (int i = 0; i < DRCurrentAuspragung.Length; i++ )
{
DataRow RowAdd = DRCurrentAuspragung[i];
_DTCurrentAuspragung.ImportRow(RowAdd);
}
You may want to use the ImportRow() method. Remember that the table you're importing rows into has to have the same structure as the table the row you're importing belongs to (column names and types)
I am trying to add data to a row in a dataset but the data is always on a new row?
I need the data to populate under its column. I need something like Ds.Tables[0].Rows[1].add("Item")
This is how i am inserting the data:
DataSet ds = new DataSet();
ds.Tables.Add("Properties");
//GPS
ds.Tables[0].Columns.Add(ArrayProperties[0].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[0].Value);
//Street Num and Name
ds.Tables[0].Columns.Add(ArrayProperties[3].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[3].Value);
//Suburb
ds.Tables[0].Columns.Add(ArrayProperties[6].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[6].Value);
//City
ds.Tables[0].Columns.Add(ArrayProperties[7].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[7].Value);
//Province
ds.Tables[0].Columns.Add(ArrayProperties[8].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[8].Value);
//Locality Map
ds.Tables[0].Columns.Add(ArrayProperties[9].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[9].Value);
//Property Type
ds.Tables[0].Columns.Add(ArrayProperties[10].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[10].Value);
Just get a new Row from the DataTable and then add that row to the table, Use DataTable.NewRow method
DataRow dr = ds.Tables[0].NewRow();
dr["Column1"] = "value";
dr["Column2"] = "value";
dr["Column3"] = "value";
ds.Tables[0].Rows.Add(dr);
You are adding row after adding each column, You may first create your data table's structure by adding all the columns and then you can get the new row using DataTable.NewRow() and later you can add that row to your data table. After adding all the columns you may also try:
ds.Tables[0].Rows.Add(ArrayProperties[0].Value,ArrayProperties[1].Value,ArrayProperties[2].Value,ArrayProperties[3].Value);
The columns collection of a Datatable regards the table structure. In your code you mix adding columns and populating fileds.
You should first create the structure (not tested and syntax errors can occur):
Dataset ds = new Dataset();
Datatable dt = new Datatable();
dt.columns.add(new Column.add(...));
...
dt.columns.add(new Column.add(...));
ds.Tables.add(dt);
And then:
Datarow r = ds.tables[0].NewRow();
r["column1"] = value1;
...
r["columnX"] = valueX;
ds.Tables[0].rows.add(r);
See this msdn article for more details.
Add the columns as you are adding. For populating rows, do the below.
foreach (DataRow row in ds.Tables[0]) // Loop over the rows.
{
row[ArrayProperties[i].FormMobiField]=ArrayProperties[0].Value;
i++;
}
If it doesn't work then let me know,
I have two data tables, dt1 & dt2. dt1 has data while dt2 is a new table. Now I want to copy some rows, satisfying particular condition, to dt2. I have tried following code, but I get this exception:
System.ArgumentException This row already belongs to another table.
foreach(DataRow dr in dt1.Rows)
{
if(Convert.ToInt32(dr["col"]) == value)
{
dt2.Rows.Add(dr);
}
}
How can I resolve this?
change dt2.Rows.Add(dr); to dt2.Rows.Add(dr.ItemArray);
You directly cannot "Add" a DataTable row from one to another since it belongs to souce Datatable. You can "Add" a newly created row to DataTable.
Hence you are getting this exception.
There are many ways to overcome this. Some are listed below
Method 1:
If you want to get a row from source Datatable and add in destination without any changes, then use ImportRow this way.
dt2.ImportRow(dr);
Method 2:
But if you want to take specific data. Then use this
foreach(DataRow dr in dt1.Rows)
{
if(Convert.ToInt32(dr["col"]) == value)
{
Datarow ndr = dt2.NewRow();
ndr["Foo"] = dr["Foo"];
//..Similarly for other rows.
dt2.Rows.Add(ndr);
}
}
Every time when you add a row to the datatable it should be different(new) row........
Datarow newRow = null;
foreach(DataRow dr in dt1.Rows)
{
if(Convert.ToInt32(dr["col"]) == value)
{
newRow = dt2.NewRow();
newRow ["A"] = dr["A"];
dt2.Rows.Add(newRow );
}
}
For testing I would like to expand my result set. I have a DataTable dt that has 7 or so results. I would like to do something like:
dt.Rows.Add(dt); a few times, just to make the data set larger.
I also tried dt.Rows.Add(dt.Rows[0]);
The first gave an error about the type, the second said the row already existed.
You need to do something like what's below. Basically generate a new row using the values from the existing row.
DataTable dt = new DataTable();
DataRow dr = dt.Rows[0];
dt.Rows.Add(dr.ItemArray);
You need to copy values to new row:
DataRow row = dt.NewRow();
row.ItemArray = dt.Rows[0].ItemArray;
dt.Rows.Add(row);
The first item fails because the function expects a DataRow param.
The second item fails, because you are trying to add an item from the table, so it will inherently exist.
Try:
DataTable dt;
DataRow dr = dt.NewRow();
dr["field"] = "Some Value";
dt.Rows.Add(dr);
Check out the DataRow Class article on MSDN
How can I copy specific rows from DataTable to another Datable in c#? There will be more than one row.
foreach (DataRow dr in dataTable1.Rows) {
if (/* some condition */)
dataTable2.Rows.Add(dr.ItemArray);
}
The above example assumes that dataTable1 and dataTable2 have the same number, type and order of columns.
Copy Specified Rows from Table to another
// here dttablenew is a new Table and dttableOld is table Which having the data
dttableNew = dttableOld.Clone();
foreach (DataRow drtableOld in dttableOld.Rows)
{
if (/*put some Condition */)
{
dtTableNew.ImportRow(drtableOld);
}
}
Try This
String matchString="ID0001"//assuming we have to find rows having key=ID0001
DataTable dtTarget = new DataTable();
dtTarget = dtSource.Clone();
DataRow[] rowsToCopy;
rowsToCopy = dtSource.Select("key='" + matchString + "'");
foreach (DataRow temp in rowsToCopy)
{
dtTarget.ImportRow(temp);
}
Check this out, you may like it (previously, please, clone table1 to table2):
table1.AsEnumerable().Take(recodCount).CopyToDataTable(table2,LoadOption.OverwriteChanges);
Or:
table1.AsEnumerable().Where ( yourcondition ) .CopyToDataTable(table2,LoadOption.OverwriteChanges);
Supported in: 4, 3.5 SP1, you can now just call a method on the object.
DataTable dataTable2 = dataTable1.Copy()
As a result of the other posts, this is the shortest I could get:
DataTable destTable = sourceTable.Clone();
sourceTable.AsEnumerable().Where(row => /* condition */ ).ToList().ForEach(row => destTable.ImportRow(row));
I've created an easy way to do this issue
DataTable newTable = oldtable.Clone();
for (int i = 0; i < oldtable.Rows.Count; i++)
{
DataRow drNew = newTable.NewRow();
drNew.ItemArray = oldtable.Rows[i].ItemArray;
newTable.Rows.Add(drNew);
}
I needed to copy rows from multiple tables with the same structure into a new table to be used as a datasource for datagridview:
// Generate DataTable[] alltables from multiple datatables
DataTable newTable = alltables[0].Clone();
foreach (DataTable dt in alltables)
{
for (int i = 0; i < dt.Rows.Count; i++)
newTable.Rows.Add(dt.Rows[i].ItemArray);
}
below sample would be the fastest way to copy one row.
each cell is being copied based on the column name.
in case you dont need a specific cell to copy then have a try catch or add if.
if your going to copy more than 1 row then loop the code below.
DataRow dr = dataset1.Tables[0].NewRow();
for (int i = 0; i < dataset1.Tables[1].Columns.Count; i++)
{
dr[dataset1.Tables[1].Columns[i].ColumnName] = dataset1.Tables[1].Rows[0][i];
}
datasetReport.Tables[0].Rows.Add(dr);
dataset1.Tables[1].Rows[0][i]; change the index 0 to your specified row index or you can use a variable if your going to loop or if its going to be logical
private void CopyDataTable(DataTable table){
// Create an object variable for the copy.
DataTable copyDataTable;
copyDataTable = table.Copy();
// Insert code to work with the copy.
}
To copy whole datatable just do this:
DataGridView sourceGrid = this.dataGridView1;
DataGridView targetGrid = this.dataGridView2;
targetGrid.DataSource = sourceGrid.DataSource;
For those who want single command SQL query for that:
INSERT INTO TABLE002
(COL001_MEM_ID, COL002_MEM_NAME, COL002_MEM_ADD, COL002_CREATE_USER_C, COL002_CREATE_S)
SELECT COL001_MEM_ID, COL001_MEM_NAME, COL001_MEM_ADD, COL001_CREATE_USER_C, COL001_CREATE_S
FROM TABLE001;
This query will copy data from TABLE001 to TABLE002 and we assume that both columns had different column names.
Column names are mapped one-to-one like:
COL001_MEM_ID -> COL001_MEM_ID
COL001_MEM_NAME -> COL002_MEM_NAME
COL001_MEM_ADD -> COL002_MEM_ADD
COL001_CREATE_USER_C -> COL002_CREATE_USER_C
COL002_CREATE_S -> COL002_CREATE_S
You can also specify where clause, if you need some condition.
There is better way to do this.
DataTable targetDataTable = new DataTable();
targetDataTable = changedColumnMetadata.AsEnumerable().Where(dataRow => entityName.Equals(dataRow["EntityName"])).CopyToDataTable();
Please try this and let me know in case of any issues.
You can do it calling the DataTable.Copy() method, for example:
DataSet ds = new DataSet();
System.Data.DataTable dt = new System.Data.DataTable();
dt = _BOSearchView.DS.Tables[BusLib.TPV.TableName.SearchView].Copy();
ds.Tables.Add(dt);
UltGrdSaleExcel.SetDataBinding(ds, dt.TableName, true);
use Merge, this will append all rows of newDataTable with oldDateTale
oldDateTale.Merge(newDataTable);