How to add column to datatable from another datatable - c#

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

Related

DataTable expression refering to other DataTable column

I have 2 DataTables, DT1 and DT2.
DT1 has columns A1, B1 and DT2 has columns A2, B2.
I'd like to add an expression to A1like A1 = A2 + B2
Is this possible to do without joining or merging the 2 DataTables, this is similar to the way spreadsheets operate?.
Is there any other way to do this, any other data structures or techniques apart from DataTable that would get this done?.
I see that a DataTable won't be able the deduce from a string the tables that the columns belong to?
Is it possible that we can add these 2 DataTables to a DataSet and then do the expression referring to tables present in the DataSet.
Edit:
I have used addition as an example however the expressions can have multiple combinations of math and logic operators and sometimes basic math functions.
See code below
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID", typeof(string));
dt1.Columns.Add("A1", typeof(int));
dt1.Columns.Add("B1", typeof(int));
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID", typeof(string));
dt2.Columns.Add("A2", typeof(int));
dt2.Columns.Add("B2", typeof(int));
DataSet ds = new DataSet()
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
foreach(DataRow row in dt1.AsEnumerable())
{
DataRow match = dt2.AsEnumerable().Where(x => x.Field<string>("ID") == row.Field<string>("ID")).First();
row["A1"] = match.Field<int>("A2") + match.Field<int>("B2");
}

Copy Datatable1 values to Datatable2 with the required columns configuration

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

To display distinct record from datatable on the basis of particular columns but result should be include all columns

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.

Looping a datatable columnwise

I have a datatable which contains data in the following format:
Let us name this datatable as dt1
ColumnA ColumnB ColumnC
-------------------------------------
President Manager President
Manager
The data in the datatable above is provided for selection for authority selection purpose as a checklist on a web form. When the items in the checklist are checked and a button click occurs, I insert the checked items into another datatable as shown below:
Let us name this datatable as dt2
----------
Manager
President
Manager
Now I need to get the Column Names from dt1(the first datatable) where the dataitems in dt2 occurs.For example, in this scenario my required output to another datatable(say dt3) would be
--------
ColumnB
ColumnC
ColumnC
In this datatable(dt3) 'ColummB' is included as the dt2(which contains the checked texts from the checklist) has the data item 'Manager' which occurs under 'ColumnB' in dt1; 'ColumnC' occurs twice as dt2 contains 'President' and 'Manager' which occurs under 'ColumnC' in dt1.
I need an efficient loop(preferably coulmnwise for dt1) so that i can compare the values of dt1 and dt2 and add them to dt3. Please note that the data items in dt1 and dt2 are not fixed as dt1 contains data from the database and dt2 has checked values from the form. Finally the row count of the dt3 should be equal to row count of dt2 (or) a new column can be added to dt2 instead of creating dt3(still maintaining the same row count).
An idea could be loop through each row and column of datatable.
Then loop through the second datatable values
If value match select the column name.
Below is just and idea what you can do
DataTable dt1;
DataTable dt2;
DataTable dt3;
string[] ar=new string....
foreach (DataRow dr in dt1.Rows)
{
foreach (DataColumn clm in dt1.Columns)
{
//loop through each value of the other table
foreach(DataRow drow in dt2.Rows)
{
string value = drow[0].ToString();
if(value==clm)
{
//add the column name into a array
DataRow row = dt3.NewRow();
row[0]=clm.ColumnName;
dt3.Rows.Add(row);
break;
}
}
}
}

Return Multiple DataTable in C# 2005

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

Categories