Mira
Mira

Reputation: 131

How to copy value of one data column into another data column in the same data table C#?

I want to copy itemarray[4] of datatable to itemarray[6] of that datatable. I used this code and I didn’t see any changes:

foreach (DataRow dr_row in dt_table.Rows)
{
    foreach (var field_value in dr_row.ItemArray)
    {
        object cell_data = field_value;
        if (dr_row.ItemArray[6].ToString() == "")
        {
            dr_row.ItemArray[6] = dr_row.ItemArray[4];
        }
        original_data += cell_data.ToString();
    }
    original_data += Environment.NewLine;
}

Upvotes: 4

Views: 3824

Answers (2)

David Limkys
David Limkys

Reputation: 5133

First of all never do this:

dr_row.ItemArray[6].ToString() == ""

Change it to this:

dr_row.ItemArray[6].ToString() == String.Empty

or:

 String.IsNullOrEmpty(dr_row.ItemArray[6].ToString())

However, that is just good practice. Now, to the problem that you are facing.

What the Itemarray does is, it creates a new array from the row, so that if you change the array, you do not change the row.

Do this:

dr_row[6] = dr_row[4];

Should work.

Upvotes: 2

KV Prajapati
KV Prajapati

Reputation: 94653

Try this,

 foreach (DataRow dr_row in dt_table.Rows)
  {
     dr_row[6] = dr_row[4];
  }

and use System.Text.StringBuilder to append data.

 System.Text.StringBuilder sb = new StringBuilder();
 sb.Append(value1);

Upvotes: 1

Related Questions