62

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)
}
TylerH
  • 20,799
  • 66
  • 75
  • 101

7 Answers7

93

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();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
23

I believe this is what you want:

DataTable dtTable = new DataTable();
foreach (DataRow dtRow in dtTable.Rows)
{
    foreach (DataColumn dc in dtRow.ItemArray)
    {

    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
glosrob
  • 6,631
  • 4
  • 43
  • 73
12

You can do it like this:

DataTable dt = new DataTable("MyTable");

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        if (row[column] != null) // This will check the null values also (if you want to check).
        {
               // Do whatever you want.
        }
     }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Glory Raj
  • 17,397
  • 27
  • 100
  • 203
11

You can check this out. Use foreach loop over a DataColumn provided with your DataTable.

 foreach(DataColumn column in dtTable.Columns)
 {
     // do here whatever you want to...
 }
Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
jle
  • 9,316
  • 5
  • 48
  • 67
7

Something like this:

 DataTable dt = new DataTable();

 // For each row, print the values of each column.
    foreach(DataRow row in dt .Rows)
    {
        foreach(DataColumn column in dt .Columns)
        {
            Console.WriteLine(row[column]);
        }
    }

http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx

Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
  • so you this will stay inside that specific row, thats the part that had me wondering about it? –  Oct 29 '11 at 13:28
  • yeap, you get the row => columns belong to datatable so you can get value of each column in the row. – Kamil Lach Oct 29 '11 at 13:33
1

In LINQ you could do something like:

foreach (var data in from DataRow row in dataTable.Rows
                     from DataColumn col in dataTable.Columns
                          where
                              row[col] != null
                          select row[col])
{
    // do something with data
}
Marthijn
  • 3,292
  • 2
  • 31
  • 48
1
int countRow = dt.Rows.Count;
int countCol = dt.Columns.Count;

for (int iCol = 0; iCol < countCol; iCol++)
{
     DataColumn col = dt.Columns[iCol];

     for (int iRow = 0; iRow < countRow; iRow++)
     {
         object cell = dt.Rows[iRow].ItemArray[iCol];

     }
}
Luca Ziegler
  • 3,236
  • 1
  • 22
  • 39