Looping through a DataTable

前端 未结 4 817
無奈伤痛
無奈伤痛 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
         foreach (DataRow row in dt.Rows) 
         {
            foreach (DataColumn col in dt.Columns)
               Console.WriteLine(row[col]);
         }
    
    0 讨论(0)
  • 2021-02-07 04:18

    Please try the following code below:

    //Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
    //Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.
    
    using (reader = cmd.ExecuteReader())
    {
    // Load the Data table object
      dataTable.Load(reader);
      if (dataTable.Rows.Count > 0)
      {
        DataColumn col = dataTable.Columns["YourColumnName"];  
        foreach (DataRow row in dataTable.Rows)
        {                                   
           strJsonData = row[col].ToString();
        }
      }
    }
    
    0 讨论(0)
  • 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({)

    0 讨论(0)
  • 2021-02-07 04:35
    foreach (DataColumn col in rightsTable.Columns)
    {
         foreach (DataRow row in rightsTable.Rows)
         {
              Console.WriteLine(row[col.ColumnName].ToString());           
         }
    } 
    
    0 讨论(0)
提交回复
热议问题