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

データテーブル内のすべてのセルの内容を変更する場合は、別のデータテーブルを作成し、「行のインポート」を使用して次のようにバインドする必要があります。別のテーブルを作成しないと、「コレクションが変更されました」という例外がスローされます。

次のコードを検討してください。

//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 に答える