【问题标题】:Looping through a DataTable循环遍历数据表
【发布时间】:2012-08-25 06:07:56
【问题描述】:

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

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

【问题讨论】:

  • 您能否详细说明您是如何“注意到这不起作用”的?它有什么问题?

标签: c# datatable dataset


【解决方案1】:
foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
} 

【讨论】:

  • 这是我一直在寻找的解决方案。非常感谢。
  • DataRow 对象可以接收一个 DataColumn 作为参数。因此,您可以简单地使用 row[col]. 而不是 row[col.ColumnName]
【解决方案2】:
     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }

【讨论】:

  • 问题在于它将重复我不想要的每个数据行的列名。基本上我希望该列显示一次,然后显示该列的所有行
【解决方案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); 
}

这将有所有以括号({)开头的单元格

【讨论】:

    【解决方案4】:

    请尝试以下代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多