Adding data to a row in a Dataset? - c#

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,

Related

How to assign one datarow values to another datarow

I want to copy first row of one DataTable to first row of another DataTable. I did as shown below but it throws error like
Property or indexer 'System.Data.DataRowCollection.this[int]' cannot be assigned to -- it is read only
DataTable dt = GetTable();
DataTable dt1 = GetTable1();
dt.Rows[0] = dt1.Rows[0];
You have to copy it field by field.
The data row within the datatable is immutable, which means that you can change the values of its fields, but not the object itself, being said that you should copy the values from you source row to the destination row.
Assuming your datatables have the same columns:
DataTable dt = GetTable();
DataTable dt1 = GetTable1();
foreach(DataColumn column in dt.Columns)
{
dt.Rows[0][column] = dt1.Rows[0][column];
}
Hope this helps.

ImportRow make the new row column missing

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();

Add DataTable Row to DataGridView without binding

I have a predefined DataGridView that I need to add rows to from a DataTable without data binding. I am trying to use the DataGridView.Rows.Add() method programmatically however, I do not know the column names of the DataTable. The columns in the DataTable are in the same order as the DataGridView but how do I add them to the DataGridView without knowing the column names?
Say your DataGridView exists but has no columns. You can do this:
foreach (DataColumn dc in yourDataTable.Columns) {
yourDataGridView.Columns.Add(new DataGridViewTextBoxColumn());
}
Then add the row data:
foreach(DataRow dr in yourDataTable.Rows) {
yourDataGridView.Rows.Add(dr.ItemArray);
}
Now, if the default textbox column isn't sufficient, you might have to create a column with a different cell template.
it seems that you want to get the column names from the DataTable and add the rows to DataGridView from DataTable rows
DataTable myDataTable = new DataTable();
//adding Columns
myDataTable.Columns.Add("colInt", typeof(int));
myDataTable.Columns.Add("colDate", typeof(DateTime));
myDataTable.Columns.Add("colString", typeof(string));
//adding Rows
myDataTable.Rows.Add(1, DateTime.Now, "Hello World");
//to get columns
foreach (DataColumn col in myDataTable.Columns)
{
var c = new DataGridViewTextBoxColumn() { HeaderText = col.ColumnName }; //Let say that the default column template of DataGridView is DataGridViewTextBoxColumn
dataGridView1.Columns.Add(c);
}
//to get rows
foreach (DataRow row in myDataTable.Rows)
{
dataGridView1.Rows.Add(row[0], row[1], row[2]);
}
anyway there's a shortcut
dataGridView1.DataSource = myDataTable;
if your DataGridView haven’t rows and columns., then just
yourDataGridView.DataSource = yourDataTable
will do all job.
if your DataGridView is already bounded to some datasource(if you using DataTable then I presume DataSource is DataTable),
then you need to edit yourDataTable -> add old rows from old DataTable(or from DataGridView if old DataTable not accessible anymore)
foreach(DataRow dr in oldDataTable.Rows)
{
yourDataTable.Rows.Add(dr);
}
yourDataGridView.DataSource = yourDataTable;
or edit oldDataTable -> add new rows from yourDataTable, something like:
DataTable dtOld = (DataTable)yourDataGridView.DataSource;
foreach(DataRow yourdr in yourDataTable.Rows)
{
dtOld.Rows.Add(yourdr);
}
yourDataGridView.DataSource = dtOld;

How to add datarows to an already existing datatable?

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);

C# datatable, duplicate data

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

Categories

Resources