次の方法で共有


DataView を使用したリレーションシップ間の移動

DataSet 内のテーブル間にリレーションシップが存在する場合は、このリレーションシップの子テーブルの行が含まれている DataView を作成できます。このような DataView を作成するには、親テーブルの行に対して DataRowViewCreateChildView メソッドを使用します。たとえば、次に示すコード例は、CategoryNameProductName によってデータをアルファベット順に並べ替えられた Categories およびこのテーブルに関連する Products を表示します。

Dim catTable As DataTable = catDS.Tables("Categories")
Dim prodTable As DataTable = catDS.Tables("Products")

' Create a relation between the Categories and Products tables.
Dim catProdRel As DataRelation = catDS.Relations.Add("CatProdRel", _
                                                     catTable.Columns("CategoryID"), _
                                                     prodTable.Columns("CategoryID"))

' Create DataViews for the Categories and Products tables.
Dim catView As DataView = New DataView(catTable, "", "CategoryName", DataViewRowState.CurrentRows)
Dim prodView As DataView

' Iterate through the Categories table.
Dim catDRV, prodDRV As DataRowView

For Each catDRV In catView
  Console.WriteLine(catDRV("CategoryName"))

  ' Create a DataView of the child product records.
  prodView = catDRV.CreateChildView(catProdRel)
  prodView.Sort = "ProductName"

  For Each prodDRV In prodView
    Console.WriteLine(vbTab & prodDRV("ProductName"))
  Next
Next
[C#]
DataTable catTable = catDS.Tables["Categories"];
DataTable prodTable = catDS.Tables["Products"];

// Create a relation between the Categories and Products tables.
DataRelation catProdRel = catDS.Relations.Add("CatProdRel", catTable.Columns["CategoryID"],
                                                            prodTable.Columns["CategoryID"]);

// Create DataViews for the Categories and Products tables.
DataView catView = new DataView(catTable, "", "CategoryName", DataViewRowState.CurrentRows);
DataView prodView;

// Iterate through the Categories table.
foreach (DataRowView catDRV in catView)
{
  Console.WriteLine(catDRV["CategoryName"]);

  // Create a DataView of the child product records.
  prodView = catDRV.CreateChildView(catProdRel);
  prodView.Sort = "ProductName";

  foreach (DataRowView prodDRV in prodView)
    Console.WriteLine("\t" + prodDRV["ProductName"]);
}

参照

DataView を使用したデータの表示 | DataView の作成と使用 | DataSet クラス | DataView クラス | DataRowView クラス