C# - Duplicate DataRows and all its childrows/relations

By , 11/5/2013
(0 ratings)
See title
//Assuming the first column in the datatable is the primary key, the second the foreign key

public static DataRow CopyRowAndRelations(Guid newParentGuid, ref DataRow dr)
	dynamic newDr = dr.Table.NewRow();

	foreach (DataColumn clm in dr.Table.Columns) {
		newDr(clm) = dr(clm);

	newDr(0) = Guid.NewGuid();
	newDr(1) = newParentGuid;

	foreach (DataRelation rel in dr.Table.ChildRelations) {
		foreach (DataRow row in dr.GetChildRows(rel.RelationName)) {
			dynamic newRow = CopyRowAndRelations(newDr(0), ref row);


	return newDr;



Log in, to comment!