简体   繁体   中英

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?

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

UPDATED to add .Rows.

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({)

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM