Mitch
Mitch

Reputation: 389

how can I add values into a new data table column in the existing rows

Here Is my problem. I am trying to take the Full Name field of my data table and split the name into first and last then add those names back into my data table in their correct positions. So far this is what I have.

DataTable DBTable = LoadMailingListContent(Location);

List<string> fullNames = DBTable.Rows.OfType<DataRow>().Select(dr => dr.Field<string>(columnName)).ToList();

DBTable.Columns.Remove(columnName);

DBTable.Columns.Add("First Name");
DBTable.Columns.Add("Last Name");

foreach (string fullname in fullNames)
{
    var names = fullname.Split(' ');
    string firstName = names[0];
    string lastName = names[1];

    //here is where I want to add the new name values into their new fields
}

Could I set a counter inside my foreach loop and add the names back in depending on the index of the row? I need help on how to add the new first and last name values back into my new fields.

thanks

Upvotes: 2

Views: 58781

Answers (4)

Vijay Kumbhoje
Vijay Kumbhoje

Reputation: 1441

Below is simple example to add column and its value to existing datatable.

string status = "ABC";
        DataColumn dc = new DataColumn("Status");
        dt.Columns.Add(dc);
        foreach (DataRow dr in dt.Rows)
        {
            dr["status"]= status;
        }
        return dt;

The resulting datatable will look like

ExistingColumn | Status

ExistingValue | ABC

Upvotes: 2

kostas ch.
kostas ch.

Reputation: 2035

Try

DataTable DBTable = LoadMailingListContent(Location);

DataColumn dc = new DataColumn("FirstName");
DBTable.Columns.Add(dc);
dc = new DataColumn("LastName");
DBTable.Columns.Add(dc);
foreach (DataRow d in DBTable.Rows)
{ 
    var names = d["fullname"].ToString().Split(' ');
    d["FirstName"] = names[0];
    d["LastName"] = names[1];
}

Upvotes: 4

Igor
Igor

Reputation: 15893

for (int iter = 0; iter < fullNames.Count; iter++)
{
  var names = fullNames[iter].Split(' ');
  string firstName = names[0];
  string lastName = names[1];
  DBTable.Rows[iter]["First Name"] = firstName;
  DBTable.Rows[iter]["Last Name"] = lastName;
}

Upvotes: 1

Z .
Z .

Reputation: 12837

DBTable["First Name"] = firstName;
DBTable["Last Name"] = lastName;

Upvotes: 0

Related Questions