How to add a new column (with value) to an already existing datatable using C#?

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 20146
Suppose we have a Datatable as under

public DataTable GetData()
{

DataTable dt = new DataTable();

//Add some columns
dt.Columns.Add(new DataColumn("ImageID", typeof(Int32)));
dt.Columns.Add(new DataColumn("ImageData", typeof(string)));

//Add some rows

//First Row
DataRow row1 = dt.NewRow();
row1("ImageID") = 1;
row1("ImageData") = "ImageData1";

//Second Row
DataRow row2 = dt.NewRow();
row2("ImageID") = 11;
row2("ImageData") = "ImageData11";

//Third Row
DataRow row3 = dt.NewRow();
row3("ImageID") = 12;
row3("ImageData") = "ImageData12";

//Fourth Row
DataRow row4 = dt.NewRow();
row4("ImageID") = 15;
row4("ImageData") = "ImageData15";

//Fifth Row
DataRow row5 = dt.NewRow();
row5("ImageID") = 18;
row5("ImageData") = "ImageData18";

//Sixth Row
DataRow row6 = dt.NewRow();
row6("ImageID") = 19;
row6("ImageData") = "ImageData19";

//Seventh Row
DataRow row7 = dt.NewRow();
row7("ImageID") = 21;
row7("ImageData") = "ImageData21";

//Add the rows to the table
dt.Rows.Add(row1);
dt.Rows.Add(row2);
dt.Rows.Add(row3);
dt.Rows.Add(row4);
dt.Rows.Add(row5);
dt.Rows.Add(row6);
dt.Rows.Add(row7);

//return the table
return dt;
}


Now we need to add a new column to it with data. We can do so as under

public void GetModifiedTable()
{
DataTable dt =GetData();
DataColumn newCol = new DataColumn("ModifiedImageID", typeof(Int32));
dt.Columns.Add(newCol);
int counter = 1;
foreach (DataRow row in destinationDT.Rows)
{
row["ModifiedImageID"] = counter;
counter++;
}
}

We have created a new column by using new DataColumn("ModifiedImageID", typeof(Int32)); and added that to the existing DataTable. Next we populated some values to it by using row["ModifiedImageID"] = counter;

Hope this helps

Comments or Responses

Login to post response