Looping through a DataTable

SpaceApple picture SpaceApple · Aug 30, 2012 · Viewed 128.2k times · Source

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 the braces :

Name (DataColumn)
Tom  (DataRow)
Peter (DataRow)

Surname (DataColumn)
Smith (DataRow)
Brown (DataRow)

foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          //output              
     }
} 

I typed that out and noticed this would not work. Can someone please advice on a better way of doing this?

Answer

Candide picture Candide · Aug 30, 2012
foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
}