I have created a datatable which has some records, now what I want is to copy the record of first datatable to another datatable.
I tried like below:
Session["AmountData"] = AmountDatatable; // 1st datatable which has data
DataTable CompanyWiseRecord = new DataTable();
for (int i = 0; i < AmountDatatable.Rows.Count; i++)
{
CompanyWiseRecord.ImportRow(AmountDatatable.Rows[i]); // 2nd datatable which does not have data
}
Kindly let me know where I am going wrong.
You directly use session Like:
DataTable CompanyWiseRecord = (DataTable)Session["AmountData"]; //Retrieving DataTable from Session.
if you are not fetching data from table one based on some condition or assign particular rows or columns then You can do it simply by using
DataTable CompanyWiseRecord=AmountDatatable;
Related
I have a datatable filled with a report from a web service. I am now trying to display the datatable in an datagridview. This is the code I use to build the datatable:
// Create DataTabe to handle the output
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("EmployeeFirstName");
dt.Columns.Add("EmployeeLastName");
dt.Columns.Add("DepartmentName");
dt.Columns.Add("DepartmentCode");
dt.Columns.Add("LocationName");
dt.Columns.Add("DivisionCode");
dt.Columns.Add("EarningName");
dt.Columns.Add("OTHours");
dt.Columns.Add("WorkDate")
Fill the new datatable:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(string.Join(",", row.ColumnValues));
}
Then I try to bind the data in the datatable to the dataGridview:
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
When I run the application it only displays the data from the first column in the datatable. Do I need a loop of sorts to work through the columns or am I just missing a step?
Yes that's cause you are adding only one value to your dt when you say dt.Rows.Add(string.Join(",", row.ColumnValues));. You should be doing something like below (assuming that ReportRow also has the columns with same names like "EmployeeFirstName" else change the names accordingly)
foreach (ReportRow row in report.Rows)
{
DataRow dr = dt.NewRow();
dr["EmployeeFirstName"] = row["EmployeeFirstName"];
dr["EmployeeLastName"] = row["EmployeeLastName"];
dr["DepartmentName"] = row["DepartmentName"];
//rest of the columns fill
//once all columns filled
dt.Rows.Add(dr);
}
dt.Rows.Add(string.Join(",", row.ColumnValues)); -> You can either add a single DataRow item or a array of objects.
From your call, you chose the later, you are adding a array of objects, except you are adding ONE SINGLE object.
string.Join(",", row.ColumnValues) is one object.
Well after sleeping I have found the issue with dropping it into an sql table... I didn't take into account that the export to a CSV and the addition of the " , " would affect the export to sql. Here is the modification of the lines of code that was the issue:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(row.ColumnValues);
}
Thank you all for your responses!
Is it possible to add a row to the middle of an existing dataset with c#? I've done a lot of searching and haven't been able to find anything on how to do this. What have I tried? I've tried searching a lot and haven't found anything like an 'insertAt' method for datasets.
Thanks
Mike
The DataSet consists of a collection of DataTable objects so I assume that you are talking about a Datatable, right? If so, it has an InsertAt method:
DataTable dt = dataset.Tables[0]; //Get first datatable from dataset
DataRow row = dt.NewRow();
//fill row
dt.Rows.InsertAt(row,3); //Insert at index 3
DataSet does not have a rows collection, so you can't add a row to it at all.
You can insert a row by index into a DataTable object using DataTable.Rows.InsertAt(row, i). If the table is in a DataSet, your syntax would be DataSet.Tables[i].Rows.InsertAt(row, 0)
In my opinion (though this could take a lot of time), you can create an array or a list array then transfer all the data there from your dataset through for loop or any loop...then put an if statement inside to check where you want to put your extra data like this:
List<string> arrayList = dataset;// i know this is not possible just showing you that you have to put all your data from dataset to array:)
List <string> newList = new List<string>();//its up to you if you want to put another temporary array or you could simply output your data from the loop.
//THE LOOP
for(int i = 0; i<=arrayList.Count(); i++){
if(i == x)//x is the index or you may change this statement its up to you
{
//do the print or pass the data to newList
newList.add(arraList[i]);//not sure about this. its been a while since the last time i use this array list..
}
}
another way is customize your query(if your pulling out some data from database)
happy coding:)
Here's a short sample of doing it:
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Table");
dt.Columns.Add("Id");
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(new object[]{i});
}
var newRow=dt.NewRow();
newRow.ItemArray=new string[]{(dt.Rows.Count/2).ToString()+".middle"};
dt.Rows.InsertAt(newRow, dt.Rows.Count / 2);
}
}
I want to know how to update a Datatable which is inside a dataset.I have a datatable in which i have details of some item.Now i want to add this into a dataset for some purpose and update it.Give me some suggesions to solve this..
this is my code:
DataRow dr;
dr = Basket_DataTable.NewRow();
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
Basket_DataTable.AcceptChanges();
Basket_DataTable is my datatable which i need to add to a dataset and update..
I believe you want to add new Rows to your existing DataTable in your DataSet. Instead of creating a new DataTable, your Basket_DataTable should refer to your data table in the data set.
Something like.
//Create new Row from your DataTable in DataSet
DataRow dr = yourDataSet.Tables["Basket_DataTable"].NewRow();
// here you can refer to your datatable with the index as well
//e.g. yourDataSet.Tables[0]
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
//Remember to add your row to the table.
yourDataSet.Tables["Basket_DataTable"].Rows.Add(dr);
In your current code you are not adding the new row to the datatable. Remember to include the row in the datatable.
If the DataTable is already in an existing DataSet, but you want to add it to another one, you need to create a copy first - A DataTable instance can only have one parent DataSet.
DataTable Basket_DataTable_copy = Basket_DataTable.Copy();
yourDataSet.Tables.Add(Basket_DataTable_copy);
Then you can do your updates on Basket_DataTable_copy
see DataTable.Copy on MSDN
how to copy only the columns in a DataTable to another DataTable?
DataTable.Clone() should do the trick.
DataTable newTable = originalTable.Clone();
If only the columns are required then DataTable.Clone() can be used. With Clone function only the schema will be copied. But DataTable.Copy() copies both the structure and data
E.g.
DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();
dt1 will have only the one column but dt2 will have one column with one row.
Datatable.Clone is slow for large tables. I'm currently using this:
Dim target As DataTable =
New DataView(source, "1=2", Nothing, DataViewRowState.CurrentRows)
.ToTable()
Note that this only copies the structure of source table, not the data.
If you want the structure of a particular data table(dataTable1) with column headers (without data) into another data table(dataTable2), you can follow the below code:
DataTable dataTable2 = dataTable1.Clone();
dataTable2.Clear();
Now you can fill dataTable2 according to your condition. :)
If you want to copy the DataTable to another DataTable of different Schema Structure then you can do this:
Firstly Clone the first DataType so that you can only get the structure.
Then alter the newly created structure as per your need and then copy the data to newly created DataTable
.
So:
Dim dt1 As New DataTable
dt1 = dtExcelData.Clone()
dt1.Columns(17).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(26).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(30).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(35).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(38).DataType = System.Type.GetType("System.Decimal")
dt1 = dtprevious.Copy()
Hence you get the same DataTable but revised structure
The DataTable.Clone() method works great when you want to create a completely new DataTable, but there might be cases where you would want to add the schema columns from one DataTable to another existing DataTable.
For example, if you've derived a new subclass from DataTable, and want to import schema information into it, you couldn't use Clone().
E.g.:
public class CoolNewTable : DataTable {
public void FillFromReader(DbDataReader reader) {
// We want to get the schema information (i.e. columns) from the
// DbDataReader and
// import it into *this* DataTable, NOT a new one.
DataTable schema = reader.GetSchemaTable();
//GetSchemaTable() returns a DataTable with the columns we want.
ImportSchema(this, schema); // <--- how do we do this?
}
}
The answer is just to create new DataColumns in the existing DataTable using the schema table's columns as templates.
I.e. the code for ImportSchema would be something like this:
void ImportSchema(DataTable dest, DataTable source) {
foreach(var c in source.Columns)
dest.Columns.Add(c);
}
or, if you're using Linq:
void ImportSchema(DataTable dest, DataTable source) {
var cols = source.Columns.Cast<DataColumn>().ToArray();
dest.Columns.AddRange(cols);
}
This was just one example of a situation where you might want to copy schema/columns from one DataTable into another one without using Clone() to create a completely new DataTable. I'm sure I've come across several others as well.
If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the datatable, but this returns void. Does Merge preserve the data? For example, if I do:
dtOne.Merge(dtTwo);
Does dtOne change or does dtTwo change and if either one changes, do the changes preserve?
I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll:
//Will Not work, How do I do this
dtAll = dtOne.Merge(dtTwo);
The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.
If you want to preserve both of the original tables, you could copy the original first, then merge:
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);
Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:
dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...
and so on.
This technique is useful in a loop where you want to iteratively merge data tables:
DataTable dtAllItems = new DataTable();
foreach(var item in items)
{
DataTable dtItem = getDataTable(item); // some function that returns a data table
dtAllItems.Merge(dtItem);
}
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);
The parameter TRUE preserve the changes.
For more details refer to MSDN.
DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;
This is what i did for merging two datatables and bind the final result to the gridview
DataTable dtTemp=new DataTable();
for (int k = 0; k < GridView2.Rows.Count; k++)
{
string roomno = GridView2.Rows[k].Cells[1].Text;
DataTable dtx = GetRoomDetails(chk, roomno, out msg);
if (dtx.Rows.Count > 0)
{
dtTemp.Merge(dtx);
dtTemp.AcceptChanges();
}
}