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
Related
I want to copy all rows in old datatable (oldDT) to a new datatable (dt) using ImportRow method. But the new row doesn't have a same column with the old one. Here is my code:
foreach (DataRow dr in oldDT.Rows)
{
MessageBox.Show(dr["tenant_no"].ToString()); //giving a correct result
dt.ImportRow(dr);
MessageBox.Show(dt.Rows[0]["tenant_no"].ToString()); //giving an error Column 'tenant_no' does not belong to table .
}
i try to use the answer C# simple way to copy or clone a DataRow? and here is my new code:
foreach (DataRow dr in oldDT.Rows)
{
MessageBox.Show(dr["tenant_no"].ToString());
DataRow newDR = oldDT.NewRow();
newDR.ItemArray = dr.ItemArray.Clone() as object[];
dt.Rows.Add(newDR); //giving an error "This row already belongs to another table."
MessageBox.Show(dt.Rows[0]["tenant_no"].ToString());
}
Anyone can help me?
Try this... this will work
DataTable dt= new DataTable();
dt= oldDT.Clone();
for (int i=0;i < oldDT.Rows.Count; i++)
{
dt.ImportRow(dataTable.Rows[i]);
}
You could use DataTable.Copy, if you are not locked into using the ImportRow :
Copies both the structure and data for this DataTable.
DataTable dt = oldDt.Copy();
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 );
}
}
I am having an datatable which is already populated. Now i want to add few rows to that datatable ,but some of rows might already exist in the datatable.I know its unneccesary but tht is the requirement.
I tried couple of things and got "the row already exist in this table : & this row belongs to some other table" .I also tried importRow ,but i guess it avoid the duplicates by dafault.
Is there any way to do that .If the datatable has 7 rows and i want to add 3 more rows whether its already exist or not. My goal is to send 10 rows to the calling function .
Or is there any other approach altogether?
UPDATE
Using
rowsToAdd.CopyToDataTable(dsCount.Tables[2], LoadOption.PreserveChanges); works but I'm not sure it's the proper way.
You can add new rows in DataTable using code below
DataRow newRow = dataTable.NewRow();
dataTable.Rows.Add(newRow);
To check for any duplicates try
if (table.Rows.Contain(PriKeyTypeValue)) /*See if a Primary Key Value is in
the table already */
continue;
else
table.Row.Add(value1, value2, value3);
If you want to be able to insert duplicate rows but do not want to have an exception thrown set-up your primary key as a unique self-incrementing int then you can insert as many duplicates as you feel like without having to check to see if the table contains that value. Just make sure that it would suffice to have duplicates. There are plenty of examples of setting a primary key just search for it (msdn has at least one). Here is an example:
DataTable table = new DataTable();
table.Columns.Add("Column", typeof(int));
DataColumn column = table.Columns["Column"];
column.Unique = true;
column.AutoIncrement = true;
column.AutoIncrementStep = 1; //change these to whatever works for you
column.AutoIncrementSeed = 1;
table.PrimaryKey = new DataColumn[] { column };
Create a new row using the NewRow() function.
var dataTable = new DataTable();
var dataRow = dataTable.NewRow();
Then add your new row to your datatable
dataTable.Rows.Add(dataRow)
I believe you can use the NewRow() function of the DataTable if you're simply appending a row to the table.
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
Will that not suffice?
The most straightforward method. After spending a few hours trying everything else.
DataRow dr = ds.Tables[0].NewRow();
dr["ColumnName1"] = "columnvalue"; //string
dr["ColumnName2"] = 123 //int
ds.Tables[0].Rows.Add(dr);
I have a DataGrid with 5 template columns,
However when I try and add some dynamically created controls into the grid, it fails, as there are no rows.
-Can i add a blank row in and use that? and how?
-Or any other way?
I'm pretty sure you have to bind to a data source. But it's easy enough to create your own DataTable and insert a row into it with some dummy info.
//pseudo code:
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("column1");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["column1"] = "value1";
dt.Rows.AddNew(dr);
myDataGrid.DataSource = dt;
myDataGrid.DataBind();
If you are using an unbound DataGridView, you can create new rows and then add them to DataGridView. Your question referred to DataGrid, but you tagged it for DataGridView.
// Sample code to add a new row to an unbound DataGridView
DataGridViewRow YourNewRow = new DataGridViewRow();
YourNewRow.CreateCells(YourDataGridView);
YourNewRow.Cells[0].Value = "Some value";
YourNewRow.Cells[1].Value = "Another value";
YourDataGridView.Rows.Add(YourNewRow);