循环访问DataTable

SpaceApple 19 c# datatable dataset

好.我有一个包含多列和多行的DataTable.

我想动态地遍历DataTable,输出应该如下所示,不包括大括号:

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              
     }
} 

我输入了它,发现这不起作用.有人可以建议更好的方法吗?

Candide.. 43

foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
} 


oopbase.. 13

     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }


小智.. 6

请尝试以下代码:

//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();
    }
  }
}