DataTable.ChildRelations Propriedade

Definição

Obtém a coleção das relações filho desta DataTable.

public:
 property System::Data::DataRelationCollection ^ ChildRelations { System::Data::DataRelationCollection ^ get(); };
[System.ComponentModel.Browsable(false)]
public System.Data.DataRelationCollection ChildRelations { get; }
[System.ComponentModel.Browsable(false)]
[System.Data.DataSysDescription("DataTableChildRelationsDescr")]
public System.Data.DataRelationCollection ChildRelations { get; }
[<System.ComponentModel.Browsable(false)>]
member this.ChildRelations : System.Data.DataRelationCollection
[<System.ComponentModel.Browsable(false)>]
[<System.Data.DataSysDescription("DataTableChildRelationsDescr")>]
member this.ChildRelations : System.Data.DataRelationCollection
Public ReadOnly Property ChildRelations As DataRelationCollection

Valor da propriedade

DataRelationCollection

Um DataRelationCollection que contém as relações filho da tabela. Será retornada uma coleção vazia se não houver nenhum objeto DataRelation.

Atributos

Exemplos

O exemplo a seguir usa a ChildRelations propriedade para retornar cada filho DataRelation em um DataTable. Cada relação é usada como um argumento no GetChildRows método para DataRow retornar uma matriz de linhas. Em seguida, o valor de cada coluna na linha é impresso.

private static void GetChildRowsFromDataRelation()
{
    /* For each row in the table, get the child rows using the
    ChildRelations. For each item in the array, print the value
    of each column. */
    DataTable table = CreateDataSet().Tables["Customers"];
    DataRow[] childRows;
    foreach(DataRelation relation in table.ChildRelations)
    {
        foreach(DataRow row in table.Rows)
        {
            PrintRowValues(new DataRow[] {row}, "Parent Row");
            childRows = row.GetChildRows(relation);
            // Print values of rows.
            PrintRowValues(childRows, "child rows");
        }
    }
}

public static DataSet CreateDataSet()
{
    // create a DataSet with one table, two columns
    DataSet dataSet = new DataSet();

    // create Customer table
    DataTable table = new DataTable("Customers");
    dataSet.Tables.Add(table);
    table.Columns.Add("customerId", typeof(int)).AutoIncrement = true;
    table.Columns.Add("name", typeof(string));
    table.PrimaryKey = new DataColumn[] { table.Columns["customerId"] };

    // create Orders table
    table = new DataTable("Orders");
    dataSet.Tables.Add(table);
    table.Columns.Add("orderId", typeof(int)).AutoIncrement = true;
    table.Columns.Add("customerId", typeof(int));
    table.Columns.Add("amount", typeof(double));
    table.PrimaryKey = new DataColumn[] { table.Columns["orderId"] };

    // create relation
    dataSet.Relations.Add(dataSet.Tables["Customers"].Columns["customerId"],
        dataSet.Tables["Orders"].Columns["customerId"]);

    // populate the tables
    int orderId = 1;
    for(int customerId=1; customerId<=10; customerId++)
    {
        // add customer record
        dataSet.Tables["Customers"].Rows.Add(
            new object[] { customerId,
            string.Format("customer{0}", customerId) });
    
        // add 5 order records for each customer
        for(int i=1; i<=5; i++)
        {
            dataSet.Tables["Orders"].Rows.Add(
                new object[] { orderId++, customerId, orderId * 10 });
        }
    }

    return dataSet;
}

private static void PrintRowValues(DataRow[] rows, string label)
{
    Console.WriteLine("\n{0}", label);
    if(rows.Length <= 0)
    {
        Console.WriteLine("no rows found");
        return;
    }
    foreach(DataRow row in rows)
    {
        foreach(DataColumn column in row.Table.Columns)
        {
            Console.Write("\table {0}", row[column]);
        }
        Console.WriteLine();
    }
}
Public Sub GetChildRowsFromDataRelation()
    ' For each row in the table, get the child rows using the
    ' ChildRelations. For each item in the array, print the value
    ' of each column.
    Dim table As DataTable = CreateDataSet().Tables("Customers")

    Dim childRows() As DataRow
    Dim relation as DataRelation
    Dim row as DataRow
    For Each  relation In table.ChildRelations
        For Each row In table.Rows
            PrintRowValues(new DataRow() {row}, "Parent Row")
            childRows = row.GetChildRows(relation)
            ' Print values of rows.
            PrintRowValues(childRows, "child rows")
        Next row
    Next relation
End Sub

Public Function CreateDataSet() As DataSet
    ' create a DataSet with one table, two columns
    Dim dataSet As DataSet
    dataSet = new DataSet()

    ' create Customer table
    Dim table As DataTable
    table = new DataTable("Customers")

    dataSet.Tables.Add(table)
    table.Columns.Add("customerId", _
        GetType(Integer)).AutoIncrement = true
    table.Columns.Add("name", GetType(String))
    table.PrimaryKey = new DataColumn() _
        { table.Columns("customerId") }

    ' create Orders table
    table = new DataTable("Orders")
    dataSet.Tables.Add(table)
    table.Columns.Add("orderId", GetType(Integer)).AutoIncrement = true
    table.Columns.Add("customerId", GetType(Integer))
    table.Columns.Add("amount", GetType(Double))
    table.PrimaryKey = new DataColumn() { table.Columns("orderId") }

    ' create relation
    dataSet.Relations.Add(dataSet.Tables("Customers").Columns("customerId"), _
        dataSet.Tables("Orders").Columns("customerId"))
    
    ' populate the tables
    Dim orderId As Integer = 1
    Dim customerId As Integer
    Dim i As Integer
    For customerId = 1 To 10
        ' add customer record
        dataSet.Tables("Customers").Rows.Add( _
            new object() { customerId, _
            string.Format("customer{0}", customerId) })
        
        ' add 5 order records for each customer

        For i = 1 To 5
            dataSet.Tables("Orders").Rows.Add( _
                new object() { orderId, customerId, orderId * 10 })
        
        orderId = orderId+1 
    Next
    Next

    CreateDataSet = dataSet
End Function

private sub PrintRowValues(rows() As DataRow, label As String)
    Console.WriteLine("\n{0}", label)
    If rows.Length <= 0
        Console.WriteLine("no rows found")
        Exit Sub
    End If

    Dim row As DataRow
    Dim column As DataColumn

    For Each row In rows
        For Each column In row.Table.Columns
            Console.Write("\table {0}", row(column))
        Next column
        Console.WriteLine()
    Next row
End Sub

Comentários

Um DataRelation define a relação entre duas tabelas. Normalmente, duas tabelas são vinculadas por meio de um único campo que contém os mesmos dados. Por exemplo, uma tabela que contém dados de endereço pode ter um único campo contendo códigos que representam países/regiões. Uma segunda tabela que contém dados de país/região terá um único campo que contém o código que identifica o país/região e é esse código que é inserido no campo correspondente na primeira tabela. A DataRelation, então, contém pelo menos quatro informações: (1) o nome da primeira tabela, (2) o nome da coluna na primeira tabela, (3) o nome da segunda tabela e (4) o nome da coluna na segunda tabela.

Aplica-se a

Confira também