Foreach row in datatable1 store in datatable2 - c#

I am trying to do a foreach loop that stores each row from datatable1 into datatable2, so foreach row in datatable1 store the row in datatable2, this is what I have so far:
public static DataTable datatable2 = new DataTable();
public void createDatatable()
{
profile p = new profile();
DataTable datatable1 = p.getResults(System.Convert.ToInt32(HttpContext.Current.Session["ID"]));
foreach (DataRow dr in datatable1.Rows)
{
datatable2 = datatable1.Copy();
}
}
This just copies the columns too which I don't want, I just want each row stored from datatable2 into datatable1

I assume dataTable1 & dataTable2 has same schema (same number of columns with similar datatype). Don't use .Copy(). Use Rows.Add to copy content as follows,
foreach (DataRow dr in dataTable1.Rows) {
dataTable2.Rows.Add(dr.ItemArray);
}

Related

Compare two data tables and insert into another table based on column name in C#

I have two data tables Table1 and Table2. I want to compare a value SourceField and insert the row of both table into a new data table.
Table #1 - Mapping table
Key SourceField
------------------
null name
A101 V1
A102 V2
A103 V3
Table #2 - Source table
Name V1 V2 V3
-----------------------
10001 1 2 3
Table #3 - Output table
Name Value Key
--------------------
10001 1 A101
10001 2 A102
10001 3 A103
Regards,
Manish
For DataTable , following solution will work for you.
I tested it. I used the same structure that you mentioned in the question.
DataTable table1 = new DataTable();
table1.Columns.Add("Key");
table1.Columns.Add("SourceField");
table1.Rows.Add("A101", "V1");
table1.Rows.Add("A102", "V2");
table1.Rows.Add("A103", "V3");
DataTable table2 = new DataTable();
table2.Columns.Add("Name");
table2.Columns.Add("V1");
table2.Columns.Add("V2");
table2.Columns.Add("V3");
table2.Rows.Add("10001", 1, 2, 3);
DataTable table3 = new DataTable();
table3.Columns.Add("Name");
table3.Columns.Add("Value");
table3.Columns.Add("Key");
// LOOP FOR COMPARING THE DIFFERENT COLUMNS AND VALUES FROM DIFFERENT DATATABLES
foreach (DataRow drtable1 in table1.Rows)
{
foreach (DataRow drtable2 in table2.Rows)
{
if ( drtable2[Convert.ToString(drtable1["SourceField"])] != null)
{
table3.Rows.Add(drtable2["Name"], drtable2[Convert.ToString(drtable1["SourceField"])], drtable1["Key"]);
}
}
}
Result (snap from Visual Studio)
UPDATE
Need to add one more condition in loop for checking blank value for Key column.
// LOOP FOR COMPARING THE DIFFERENT COLUMNS AND VALUES FROM DIFFERENT DATATABLES
foreach (DataRow drtable1 in table1.Rows)
{
foreach (DataRow drtable2 in table2.Rows)
{
if (drtable2[Convert.ToString(drtable1["SourceField"])] != null && Convert.ToString(drtable1["Key"]).Trim() != string.Empty)
{
table3.Rows.Add(drtable2["Name"], drtable2[Convert.ToString(drtable1["SourceField"])], drtable1["Key"]);
}
}
}
You can create a new DataSet:
DataSet dset = new DataSet();
DataTable datatable3 = new DataTable("OutputTable");
datatable3.Columns.Add(new DataColumn("Name",typeof(string)));
datatable3.Columns.Add(new DataColumn("Value", typeof(int)));
datatable3.Columns.Add(new DataColumn("Key", typeof(string)));
//do a foreach or any other operation here
//you can add a new row to the datatable like that:
drow["Name"] = "10001";
drow["Value"] = 3;
drow["Key"] = "A103";
DataRow drow = datatable3.NewRow();
datatable3.Rows.Add(drow);
//after adding ALL rows, you have to add the datatable to the dataset
dset.Tables.Add(datatable3);
Loop through an existing dataset (I suppose you already have ds1 and ds2 as seperate datatables):
foreach (DataRow row1 in datatable1.Rows)
{
foreach (DataRow row2 in datatable2.Rows)
{
//example comparasion
if (row1["SourceField"] == row2["SourceField")
{
datatable3.Rows.Add(....) //see above examples how to add a row
}
}
}

I have a list of datatable, how can I copy that list into single datatable in c#

public DataTable LoadPaymentsList()
{
List< DataTable > lstDts = new List< DataTable >();
// Copy into dt
Datatable dt=new Datatable();
return dt;
}
I don't think there's a better way than simple Row- and Column-Adding:
DataTable mergedTable = new DataTable();
List<DataTable> tableCollection = new List<DataTable>();
/*---------------------------------*/
bool columnsAdded = false;
foreach (DataTable table in tableCollection)
{
if (!columnsAdded)
{
foreach (DataColumn column in table.Columns)
{
mergedTable.Columns.Add(column);
}
columnsAdded = true;
}
foreach (DataRow row in table.Rows)
{
mergedTable.Rows.Add(row);
}
}
You want to have a look into merging tables . Check this for further info on dataTable Merging, http://www.c-sharpcorner.com/UploadFile/0c1bb2/merging-multiple-datatables-into-single-datatable-using-asp/
//merging first data table into second data table
dt2.Merge(dt);
dt2.AcceptChanges();

Checking value in column foreach row

The DataTable (dt) stores the retrieved values of carID's and makes so it stores like 3 rows within the DataTable, I also have another DataTable called dt2 which also stores carID's and makes, I am trying to loop through each row in the dt to see if any carID stored in the dt exists in any of the rows in dt2, here is what I have so far:
DataTable dt = w.getUserCars(userID);
foreach (DataRow dr in dt.Rows)
{
string carID = dr["carID"].ToString();
}
How do I do this?
You should be able to achieve this using DataTable.Select() method. You are on the right track. You just need to add the method to find the Row(s) in dt2.
DataTable dt = w.getUserCars(userID);
DataRow[] foundRows;
foreach (DataRow dr in dt.Rows)
{
string carID = dr["carID"].ToString();
foundRows = dt2.Select("carID = " + carID);
// do stuff here with foundRows
foreach (DataRow r in foundRows)
{
r.Delete();
}
}

Delete Row From Data Table

I want to Delete the Multiple records from the DataTable
For example :
in my case PaperId is Repeating several Times.I want to Delete it all Duplicate records.
i have written code but loop is giving error
DataSet ds = new DataSet();
sqlDad.Fill(ds);
DataTable dt1 = new DataTable();
ds.Tables.Add(dt1);
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = dt1;
List<DataRow> rowsToDelete = new List<DataRow>();
foreach(DataRow dr in ds.Tables[0].Rows)
{
int r = ds.Tables[0].Columns.Count;
string x = dr.ItemArray[0].ToString();
int counter = 0;
foreach (DataRow dr1 in ds.Tables[0].Rows)
{
if (x == dr1.ItemArray[0].ToString())
{
counter++;
}
if (counter > 1)
{
rowsToDelete.Add(dr1);
foreach (DataRow row in rowsToDelete)
{
dt2.Rows.Remove(row);
}
dt2.AcceptChanges();
rowsToDelete.Clear();
}
}
Using the DefaultView of the DataTable and setting the sort order on the column that you don't want repeats to appear. You could loop over the rows and delete all the rows after the first one
// Work on the first table of the DataSet
DataTable dt1 = ds.Tables[0];
// No need to work if we have only 0 or 1 rows
if(dt1.Rows.Count <= 1)
return;
// Setting the sort order on the desidered column
dt1.DefaultView.Sort = dt1.Columns[0].ColumnName;
// Set an initial value ( I choose an empty string but you could set to something not possible here
string x = string.Empty;
// Loop over the row in sorted order
foreach(DataRowView dr in dt1.DefaultView)
{
// If we have a new value, keep it else delete the row
if(x != dr[0].ToString())
x = dr[0].ToString();
else
dr.Row.Delete();
}
// Finale step, remove the deleted rows
dt1.AcceptChanges();
Try This
DataRow[] rows;
rows=dataTable.Select("UserName = 'ABC'"); // UserName is Column Name
foreach(DataRow r in rows)
r.Delete();
If you want to remove the entire row from DataTable ,
try this
DataTable dt = new DataTable(); //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'");
foreach (DataRow row in rows)
dt.Rows.Remove(row);

collection to Datatable and dataset

i work on C# vs05 ...
DataTable dt=CreateTable(_oGeneralReports);//collection _oGeneralReports
i want a method that Converting a Collection into a DataTable ..dt contain the collection value.....help me to get this
You'll have to make a new data table and manually add all the columns to it, then loop through the collection adding each item to the table. e.g
public DataTable CreateTable(ICollection items)
{
DataTable table = new DataTable();
table.Columns.Add("Column1", typeof(int));
table.Columns.Add("Column2", typeof(string));
foreach (Item item in items)
{
DataRow row = table.NewRow();
row["Column1"] = item.Column1;
row["Column2"] = item.Column2;
table.Rows.Add(row);
}
return table;
}

Categories

Resources