error add a datatable row to another datatable - c#

I have datatable1 which has 11 columns and 100,000 rows.. I would like to do a check to see if the text in column one starts with "one" and if it does, add that row into the second datatable. I have done the below but yet still it does not work.. I get the error that the row belong to another table
foreach (DataRow r in queryDataTable.Rows)
{
if (r[0].ToString().StartsWith(queryString))
{
dt.ImportRow(r);
}
}

You cannot directly import the row of one table into another datatable. You need to create a new row and then copy the row.
Try this -
dt.Rows.Add(r.ItemArray)

Instead of your for loop, you may use LINQ to select those rows which StartsWith queryString and then you can use CopytoDataTable method to create a new table for the selected rows.
var NewTable = queryDataTable.AsEnumerable()
.Where(r => r.Field<string>(0).StartsWith(queryString))
.CopyToDataTable();
Remember to include using System.Linq; at the top.

Related

how to update datarow in datatable using LINQ C#?

i want to update datatable(dtTaskandBugs) on some condition.
want to update storyid of all the row in the datatable when the id(which is a column of the Datatable) is passed as paramter to the function GetStoryid.
this is my code below it's not working (nothing happening)
dtTaskandBugs.Select(string.Format("Storyid = '{0}'", dtTaskandBugs.Rows)).ToList<DataRow>().ForEach(
r =>
{
r["Storyid"] = GetStoryid(r["Id"]);
});
The error is here:
string.Format("Storyid = '{0}'", dtTaskandBugs.Rows)
You are passing the number of rows in this table as argument to DataTable.Select which filters the rows, so probably doesn't return any rows.
I suggest a simple foreach-loop since you want to update all rows:
foreach(DataRow row in dtTaskandBugs.Rows)
row ["Storyid"] = GetStoryid(row["Id"]);

Add columns into a DataTable inside a loop

I'd like to know if there is a way to automatically add columns in a DataTable inside a foreach loop? That is what I mean with "automatically".
I had in mind something like this:
DataTable dt = new DataTable();
foreach (var item in model.Statistik)
{
dt.Columns.Add();
row = dt.NewRow();
row[//Name of column goes here] = // either item or item.property;
dt.Rows.Add(row);
}
This is much more efficient than explicitly name every column before the for each loop. Because, what happens if some property changes or gets deleted, etc.? This is therefore, something I wish to get rid of.
I don't think you understand how dt.Columns and dt.Rows are related. There is one set of Columns for a DataTable. Every Row in the DataTable has all the matching columns - you don't have unique Columns in each Row. So every time you do dt.Columns.Add you are adding a column to every Row, old or new.
Also, how do you expect Row[<name of column>] to work if you don't specify the name to the DataTable?

i want to pass value from another datatable

I am having one datatable to that table i want to pass value from another datatable.
for example:-
datatable1 in this
i want to pass value from
datatable2.row[0]["colname"]
i tried like :-
tblvdr.Rows[0]["item_Vendorname"] = dttemp.Rows[0]["item_Vendorname"];
error message:-
its showing error for No row at o position
DataRow tblvdrRow = tblvdr.NewRow();
tblvdrRow["item_Vendorname"]= dttemp.Rows[0]["item_Vendorname"];
tblvdr.Rows.Add(tblvdrRow);
It looks like your data table tblvrd does not have any row. For this use
DataRow newRow = tblvdr.NewRow();
One tme a new row is generated you can populate it from the row in another table. Naturally you need generate new row in tblvdr for every row in dttemp

How to make column names the first row?

I have a query using dynamic pivot, so the column names change based on the data. My code generates a .csv file based on the result of the query. I don't know how I can make the header, as I cannot hard-code column names. Is it possible somehow to make the header of the query result the first row of the recordset?
Thanks.
ADDED: Just realized that I don't even know how to fetch the data in my C# code if I don't know what columns I have... So that I cannot do something like this:
result.AddRange(from DataRow dr in dt.Rows
select new DailyTransactionSheet
{
Serve = Convert.ToInt32(dr["Serve"]),
Remits = Convert.ToInt32(dr["Remits"]),
List = Convert.ToInt32(dr["List"]),
Billing = Convert.ToInt32(dr["Billing"]),
DollarSent = Convert.ToInt32(dr["DollarSent"]),
FileAck = Convert.ToInt32(dr["FileAck"]),
});
}
as per comments:
basically you need to execute query and fetch information about columns form it, depending on how your're executing it, there can be several options:
SQLDataReader to fetch results, you can get column information from GetSchemaTable.Columns GetSchemaTable
or
SqlDataAdapter.Fill(DataSet) DataSet.Tables[0].Columns - these methods and properties you should read about DataSet.Tables
here is example from msdn:
private void PrintRows(DataSet dataSet)
{
// For each table in the DataSet, print the row values.
foreach(DataTable table in dataSet.Tables)
{
foreach(DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
}

how to update a ADO.NET DataRow in DataTable with another DataRow?

I want to do this:
public void UpdateDataRowsToDataTable(string tableName, List<DataRow> rows)
{
foreach (DataRow row in rows)
{
// this method does not exist!!
_dataSet.Tables[tableName].Rows.Update(row);
}
}
I need a method that finds a row (maybe by primary key) and updates changed rows to the row in DataTable.
The only possibility what I know is to use Select (or Find) and then maybe iterate all columns and give them new values. Please tell me that this cannot be true!
Although the question is not quite clear it sounds like you have a group of rows from one table and want to update the equivalent rows in another datatable. If this is the case they you can just use the find method and manually update them as you suggested, or alternatively, add the new rows to another table and merge them (there are all sorts of options for merging two data tables). Merging however will just do the same thing under the hood (i.e. find by primary key and update the columns).
Another way would be to just replace the row and set its status to modified datarow.SetModified()
Or you can delete the old one and add the new one...
Could you use boxing to do that if your datatables are the same.
DestDataset.DestDataTable newChildRecords =
(DestDataset.DestDataTable)_dataset.Tables[tableName].GetChanges(DataRowState.Added);
If you are using dataAdapter...
foreach (DataRow row in rows)
{
Row.BeginEdit();
//Do your stuff
Row.EndEdit();
}
dataAdapter.Update(_dataSet, "yourTable");
Another option is to use the ItemArray property to update the DataRow instance. The only thing is that you still have to select the proper rows. Also, note that you have to change the whole ItemArray instead of its elements in order to have the modification reflected in the DataTable.
foreach (DataRow row in rows)
{
// Select the row
var rows = _dataSet.Tables[tableName].Select(string.Format("Table_ID = {0}", row["Table_ID"]));
// Update the row
if (0 < rows.Length)
rows[0].ItemArray = (object[])row.ItemArray.Clone();
}
Regardless of the way you chose to update the DataRow, you can put the whole thing in an extension method.

Categories

Resources