21

好。我有一个包含多列和多行的 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              
     }
} 

我把它打出来,发现这行不通。有人可以就这样做的更好方法提出建议吗?

4

4 回答 4

54
foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
} 
于 2012-08-30T13:39:09.450 回答
14
     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }
于 2012-08-30T13:39:55.513 回答
9

请尝试以下代码:

//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();
    }
  }
}
于 2015-02-19T07:42:38.310 回答
3

如果要更改数据表中每个单元格的内容,那么我们需要创建另一个数据表并使用“导入行”将其绑定如下。如果我们不创建另一个表,它会抛出一个异常,说“Collection was Modified”。

考虑以下代码。

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

这将使所有单元格都以 Paranthesis({) 开头

于 2014-01-16T10:16:49.360 回答