Przeczytaj w języku angielskim

Udostępnij za pośrednictwem


Elementy ChildView i relacje

Jeśli relacja istnieje między tabelami w obiekcie DataSet, można utworzyć DataView wiersze zawierające wiersze z powiązanej tabeli podrzędnej przy użyciu CreateChildView metody DataRowView dla wierszy w tabeli nadrzędnej. Na przykład poniższy kod wyświetla pozycje Kategorie i powiązane z nimi produkty w kolejności alfabetycznej posortowane według kategoriiName i ProductName.

DataTable catTable = catDS.Tables["Categories"];  
DataTable prodTable = catDS.Tables["Products"];  
  
// Create a relation between the Categories and Products tables.  
DataRelation relation = 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(relation);  
  prodView.Sort = "ProductName";  
  
  foreach (DataRowView prodDRV in prodView)  
    Console.WriteLine("\t" + prodDRV["ProductName"]);  
}  

Zobacz też