Looping through a DataTable

前端 未结 4 820
無奈伤痛
無奈伤痛 2021-02-07 03:51

Well. I have a DataTable with multiple columns and multiple rows.

I want to loop through the DataTable dynamically basically the output should look as follows excluding

4条回答
  •  佛祖请我去吃肉
    2021-02-07 04:18

    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 don't 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({)

提交回复
热议问题