Alex Gordon
Alex Gordon

Reputation: 60751

c# looping through datatable, changing data

i need to loop through one of the columns of my datatable and do some string manipulation to it. can someone please give me an example of how i would loop through the table and update some data?

Upvotes: 7

Views: 41499

Answers (4)

Chris
Chris

Reputation: 377

The same thing except using a for loop. It's really a matter of preference. Try the following code..

for (int i = 0; i <= myDataTable.Rows.Count - 1; i++){
                    myDataTable.Rows[i]["ColumnName" Or IndexNumber] = value;
}

Upvotes: 1

Deepak Kothari
Deepak Kothari

Reputation: 1753

If You want to change a specified column you can use the above code,but if you want to change the contents of each and every cell in a datatable then we need to Create another Datatable and bind it as follows using "Import Row",If we dont create another table it will throw an Exception saying "Collection was Modified".

Consider the following code.

    //New Datatable created which will have updated cells
            DataTable dtUpdated=new DataTable();
            //This gives similar schema to the new datatable
            dtUpdated = dtReports.Clone();
                foreach (DataRow row in dtReports.Rows)
                {
                    for (int i = 0; i < dtReports.Columns.Count; i++)
                    {
                        string oldVal = row[i].ToString();
                        string newVal = "{"+oldVal;
                        row[i] = newVal;
                    }
                    dtUpdated.ImportRow(row); 
                }

This will have all the cells preceding with Paranthesis({)

Upvotes: 1

mint
mint

Reputation: 3433

foreach (DataRow row in MyDataTable.Rows)
{
 row["columnNameHere" Or index] = value;
}

Upvotes: 24

GendoIkari
GendoIkari

Reputation: 11914

foreach (DataRow row in myDataTable.Rows)
{
    //do what you need to calculate myNewValue here
    row["myColumn"] = myNewValue;
}

UPDATED to add .Rows.

Upvotes: 10

Related Questions