Search code examples
c#foreach

How to 'foreach' a column in a DataTable using C#?


How do I loop through each column in a datarow using foreach?

DataTable dtTable = new DataTable();
MySQLProcessor.DTTable(mysqlCommand, out dtTable);

foreach (DataRow dtRow in dtTable.Rows)
{
    //foreach(DataColumn dc in dtRow)
}

Solution

  • This should work:

    DataTable dtTable;
    
    MySQLProcessor.DTTable(mysqlCommand, out dtTable);
    
    // On all tables' rows
    foreach (DataRow dtRow in dtTable.Rows)
    {
        // On all tables' columns
        foreach(DataColumn dc in dtTable.Columns)
        {
          var field1 = dtRow[dc].ToString();
        }
    }