Copy data from Datatable1 to Datattable2 only for specific columns. I have a method with List of column vlaues and Datatable as input. I need to get all the columns from input datatable and copy to new datatble.
/*Input:
columnNames in list : column1,column2,column3
datatable1 : column1,column2,column5,column6,column3
Output:
datatble2 : column1,column2,column3 (columns from list need to be copied from datatble1 to datatble2 and return datatble2)
*/
public DataTable CopyFromDatatbale(List<string> columnNames,DataTable datatable1)
{
DataTable datatble2=new DataTable();
/*
Code to copy the data from datatable1 to datatble2 with specific columns
*/
}
This is the code i am looking for...Copying data from DataTable1 to DataTable2 for specified columns .Finally in the datatable2 i have all the columns from datatble1 (Only specific columns)
//Copy Columns from Datatable1 to Datatble2 based on columns on columnList
DataView dtView = new DataView(dataTable1);
DataTable dataTable2= new DataTable();
var getColumnNamesCommaSeperated = columnList.Select(x => x.columnNames).ToArray();
dataTable2= dataTable1.Select().CopyToDataTable()
.DefaultView.ToTable(false, getColumnNamesCommaSeperated);
Related
I have a requirement where I need to copy the existing DataTable rows/values to the new DataTable,
New DataTable is of custom(different column names) structure/schema as we need this new DataTable data to be exported to Excel file later.
To copy the required column values to the new DataTable I have created string Array which contains required column names(columns from which we need to copy data to new DataTable) of existing DataTable, given below.
string[] selectedColumns = new[] { "SUPPLIER_NAME", "SUPPLIER_NO", "CONFIRMATION_NO", "RELEASE_NO", "WCO_INVOICE_NO",
"CUSTOMER_BILLED", "BALANCE_TOBILL", "SUPP_INVOICE_NO", "SUPPLIER_PAID", "BALANCE_COST" }; //TODO Add columns "WCO_INVOICE_DATE", "SUPPLIER_INVOICE_DATE" later.
For getting the required DataTable, I have created a method which will be called like below by passing existing DataTable and selected columns of existing DataTable column names as an parameters.
DataTable _dtPrjLedgerExportData = ControllerClass.dtProjectLedgerExport(dtfilter, selectedColumns);
ControllerClass Class dtProjectLedgerExport method will return the newly created DataTable i.e. DataTable with the customize Column names and the values pulled from existing DatTable,
New DataTable additionally contain two new columns (WCO_Invoice_Date, Supplier_Invoice_Date) with default blank values (set from the code).
public static DataTable dtProjectLedgerExport(DataTable dtToExport, string[] selectedColumns)
{
DataTable dt = new DataTable();
dt.Columns.Add("Supplier");
dt.Columns.Add("Supplier_No");
dt.Columns.Add("Confirmation_Number");
dt.Columns.Add("Release_Number");
dt.Columns.Add("WCO_Invoice_No");
dt.Columns.Add("WCO_Invoice_Date");
dt.Columns.Add("Customer_Billed_Amt");
dt.Columns.Add("Balance_Remaining_to_Bill");
dt.Columns.Add("Supplier_Invoice_Number");
dt.Columns.Add("Supplier_Invoice_Date");
dt.Columns.Add("Supplier_Paid_Amt");
dt.Columns.Add("Remaining_Cost_Dollar_Balance");
//temporarily set default value for non-existing rows
dt.Columns["WCO_Invoice_Date"].DefaultValue = string.Empty;
dt.Columns["Supplier_Invoice_Date"].DefaultValue = string.Empty;
//Copy rows to dt
if (dtToExport != null && dtToExport.Rows.Count > 0)
dt = new DataView(dtToExport).ToTable(false, selectedColumns);
return dt;
}
Problem:
The above code is not working as expected it is returning Data of existing DataTable with the same structure.
What changes are required in above code to get the expected result?
I'd use this approach:
public static DataTable DtProjectLedgerExport(DataTable dtToExport, string[] selectedColumns, params string[] additionalColumns)
{
DataTable dt = dtToExport.Copy(); // add columns and data
List<DataColumn> removeColumns = dt.Columns.Cast<DataColumn>()
.Where(c => !selectedColumns.Contains(c.ColumnName, StringComparer.InvariantCultureIgnoreCase))
.ToList();
removeColumns.ForEach(dt.Columns.Remove);
foreach (string colName in additionalColumns)
{
DataColumn newColumn = new DataColumn(colName);
newColumn.DefaultValue = string.Empty;
dt.Columns.Add(newColumn);
}
return dt;
}
After stating in the comments that you have different column names in each table...(Seriously that's a critical piece of information lol)! The only way is to basiaclly map the values yourself for each column like so.
public static DataTable dtProjectLedgerExport(DataTable dtToExport)
{
DataTable dt = new DataTable();
dt.Columns.Add("Supplier");
dt.Columns.Add("Supplier_No");
dt.Columns.Add("Confirmation_Number");
dt.Columns.Add("Release_Number");
dt.Columns.Add("WCO_Invoice_No");
dt.Columns.Add("WCO_Invoice_Date");
dt.Columns.Add("Customer_Billed_Amt");
dt.Columns.Add("Balance_Remaining_to_Bill");
dt.Columns.Add("Supplier_Invoice_Number");
dt.Columns.Add("Supplier_Invoice_Date");
dt.Columns.Add("Supplier_Paid_Amt");
dt.Columns.Add("Remaining_Cost_Dollar_Balance");
foreach (var expRow in dtToExport.Rows)
{
var row = dt.NewRow();
row["Supplier"] = expRow["Supplier_Name"];
//repeat for all columns you want.
dt.Rows.Add(row);
}
return dt;
}
Well, of course, because you finally override dt completely. You should enumerate the rows in dtToExport in a loop and create new rows in dt and assign the values for every field you need.
I have two data tables dt1 and dt2, both share a common column. How to map the common column and add a new column with data to data table dt1.
DataTable dt1=new DataTable();
DataTable dt2=new DataTable();
sqlDataAdapter da1=new sqlDataAdapter("select col1,col2,col3,col4 from table",connection);
dataset ds1=new dataset();
da1.fill(ds);
dt1=ds.tables[0];
similarly for dt2 the select statement is "select col1,somecol from sometable" rest is the same as dt1.
for dt1 the output is: and the output for dt2
col1 col2 col3 col4 col1 somecol
1 2 3 4 1 true
2 5 6 ... 2 false..
i tried like below:
datatable dtTotal=new datatable();
dtTotal=dt1.clone();
foreach(datacolumn col in dt2.columns)
{
if(col.columnname=="somecol")
{
dtTotal.columns.add("somecol");
dtTotal.columns["somecol"].Datatype=col.Datatype;
}
}
foreach(datarow dr in dt1.rows)
{
dtTotal.importrows(dr);
}
//here a column is added but i don't understand how to import data into that column
I want to have a outpu like below:
col1 col2 col3 col4 somecol
1 2 3 4 true
2 5 6 7 false...
I cannot write a simple join while selecting the the data itself, because the dt2 data is coming from more complex calculations. so I have to do it at datatable level only.
if number of rows in dt1 doesnt match with number of rows in dt2 then dt2 should be added new rows with default value false.
You can use the DataTable.Merge method. The command dt1.Merge(dt2) adds to dt1 the additional columns and the additional data records from dt2. The data from dt2 will overwrite the data from dt1 that share the same primary key value and the same column name.
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
// Fill the data tables
...
// Set the default value for boolean column
dt2.Columns[4].DefaultValue = false;
// Set the primary keys
dt1.PrimaryKey = new DataColumn[] { dt1.Columns[0] }; // Use the appropriate column index
dt2.PrimaryKey = new DataColumn[] { dt2.Columns[0] }; // Use the appropriate column index
// Merge the two data tables in dt1
dt1.Merge(dt2);
i want to get distinct rows from dt on the basis of particulars columns but result should be displayed with all columns.
Here is code this returning all distinct rows but not binding "Quantity" column of default table:
public static DataTable GetDistinctRecords(DataTable dt)
{
DataView view = new DataView(dt);
DataTable distinctValues = dt.DefaultView.ToTable(true, "ContainerCode", "ProductSKU", "CompanyId", "YearId", "MonthId");
return distinctValues;
}
My datatable dt has "ContainerCode", "ProductSKU", "CompanyId", "YearId", "MonthId","Quantity" this columns,i want distict record except using Quatity but my new datatable should display this quantity column.
I have a DataTable dtData
ID name
bs2 bach
js5 hash
lk3 kom
and I have a string IDorder which contains
js5,bs2,lk3
Now I want to reorder my DataTable rows by the order of ID's in IDorder
Expected OutPut
ID name
js5 hash
bs2 bach
lk3 kom
How can I achieve this in C# ?
string IDorder = "js5,bs2,lk3";
DataTable dtData = new DataTable();
//create columns for datatable ID and name
var ordered = dtData.AsEnumerable().OrderBy(x => IDorder.IndexOf(x["ID"]));
I have table1 and table2 in a class..
public DataTable sampletable (DataTable table1,DataTable table2)
{
// How to return the two table(table1 and table2)
}
Advance thank you
public DataTable[] sampletable (DataTable table1,DataTable table2)
{
return new DataTable[] { table1, table2 };
}
Use an array. And to retrieve a particular table:
DataTable[] dtArray = sampletable (YourFirstDt, YourSecondDt);
DataTable table1 = dtArray[0];
DataTable table2 = dtArray[1];
Assuming they have the same schema, you can use the DataTable.Merge Method
public DataTable sampletable(DataTable table1, DataTable table2)
{
table1.Merge(table2);
return table1;
}
The Merge method is used to merge two DataTable objects that have
largely similar schemas. A merge is typically used on a client
application to incorporate the latest changes from a data source into
an existing DataTable. This allows the client application to have a
refreshed DataTable with the latest data from the data source.
The merge operation takes into account only the original table, and the
table to be merged. Child tables are not affected or included. If a
table has one or more child tables, defined as part of a relationship,
each child table must be merged individually.
When merging a new source DataTable into the target, any source rows
with a DataRowState value of Unchanged, Modified, or Deleted, is
matched to target rows with the same primary key values. Source rows
with a DataRowState value of Added are matched to new target rows with
the same primary key values as the new source rows.
You can use DataSet , Create a new DataSet and Add the multiple tables to it ,
For Eg-
DataSet Ds = new DataSet();
DataTable Dt1= new DataTable();
Ds.Tables.Add(Dt1)
you can add multiple tables and to access the datatable you can use the index ( eg -
Ds.Tables[0])
Hope this answers your question!!.
public DataSet Getdatasettables()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
return ds;
}