Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a data table dt having 2 columns Name and Marks



NAME MARK

A 10

B 20

C 30

D 40



I have to copy Marks to Name without deleting names data so final result should be:-

NAME MARK

A 10

B 20

C 30

D 40

10

20

30

40

How can I achive this? i have tried below code but its deleteing existing data

What I have tried:

for (int k = 0; k < dt.Rows.Count; k++)
  {
    dt1.Rows[k]["Name"] = dt2.Rows[k]["Marks"]; // overwriting Name values .but I need both values in Name column
    
  }
Posted
Updated 23-Dec-21 0:01am
Comments
0x01AA 22-Dec-21 7:43am    
Looks like you need to insert new records then...
[no name] 22-Dec-21 12:45pm    
how colud be do

1 solution

We have no idea where dt1 and dt2 came from - there is no need to clone your datatable to get at the data, just loop through your existing rows and add new rows to the end of table for each of the existing rows.

You need to capture the current size of the datatable and not use dt.Rows.Count in your for loop - why? Because you are going to add more rows to your datatable.

Your code could look like this
C#
using System;
using System.Data;

public class Program
{
	public static void Main()
	{
		
		Demo d = new Demo();
		//Create our demo table and populate it with marks for A,B,C,D
		DataTable dt = d.createDt("demo");

		//Capture the CURRENT size of the DataTable
		int dtsize = dt.Rows.Count;
		
		for (int k = 0; k < dtsize; k++)
		{
			DataRow dr;
			dr = dt.NewRow();
        	dr["name"] = dt.Rows[k]["mark"];
        	dt.Rows.Add(dr);
		}

		for (int k = 0; k < dt.Rows.Count; k++)
			Console.WriteLine("{0} : {1}\n", k, dt.Rows[k]["name"]);
	}

}
A word of warning about the line
C#
dr["name"] = dt.Rows[k]["mark"];
If you have created your DataTable with the marks column as an integer then you should really convert the mark to a string before inserting it into a name i.e.
C#
dr["name"] = dt.Rows[k]["mark"].ToString();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900