Share via


如何:访问相关数据表中的记录

如果数据集中的表是相关的,则使用 DataRelation 对象可以使用其他表中的相关记录。例如,可以使包含 Customers 和 Orders 表的数据集可用。

通过调用父表中的 DataRowGetChildRows 方法,可以使用 DataRelation 对象定位相关记录;此方法返回相关子记录的数组。还可以调用子表中的 DataRowGetParentRow 方法;此方法从父表返回单个 DataRow

本帮助页提供使用类型化数据集的示例。有关在非类型化数据集中定位关系的信息,请参见 Navigating a Relationship between Tables

说明说明

如果在 Windows 窗体应用程序中工作并使用数据绑定功能显示数据,则设计器生成的窗体可以为应用程序提供足够的功能。有关更多信息,请参见 在 Visual Studio 中将控件绑定到数据 上的页(具体来说是 如何:在 Windows 窗体应用程序中显示相关数据演练:在 Windows 窗体上显示相关数据)。

下面的代码示例演示如何在类型化数据集的关系中上下移动。它们使用类型化 DataRow (NorthwindDataSet.OrdersRow) 和生成的 FindByPrimaryKey (FindByCustomerID) 方法定位所需行并返回相关记录。该示例仅当您具有以下内容时才能正确编译和运行:

  • 包含 Customers 表的数据集(名为 NorthwindDataSet)的实例

  • Orders 表

  • 使可用于代码范围的两个表相关的关系(名为 FK_Orders_Customers)

此外,这两个表都需要填入要返回的所有记录的数据。

访问相关记录

返回选定父记录的子记录

  • 调用特定 Customers 数据行的 GetChildRows 方法,并从 Orders 表返回一个行数组:

    Dim customerID As String = "ALFKI"
    Dim orders() As NorthwindDataSet.OrdersRow
    
    orders = CType(NorthwindDataSet.Customers.FindByCustomerID(customerID).
        GetChildRows("FK_Orders_Customers"), NorthwindDataSet.OrdersRow())
    
    MessageBox.Show(orders.Length.ToString())
    
    string custID = "ALFKI";
    NorthwindDataSet.OrdersRow[] orders;
    
    orders = (NorthwindDataSet.OrdersRow[])northwindDataSet.Customers.
        FindByCustomerID(custID).GetChildRows("FK_Orders_Customers");
    
    MessageBox.Show(orders.Length.ToString());
    

返回选定子记录的父记录

  • 调用特定 Orders 数据行的 GetParentRow 方法,并从 Customers 表返回单个行:

    Dim orderID As Integer = 10707
    Dim customer As NorthwindDataSet.CustomersRow
    
    customer = CType(NorthwindDataSet.Orders.FindByOrderID(orderID).
        GetParentRow("FK_Orders_Customers"), NorthwindDataSet.CustomersRow)
    
    MessageBox.Show(customer.CompanyName)
    
    int orderID = 10707;
    NorthwindDataSet.CustomersRow customer;
    
    customer = (NorthwindDataSet.CustomersRow)northwindDataSet.Orders.
        FindByOrderID(orderID).GetParentRow("FK_Orders_Customers");
    
    MessageBox.Show(customer.CompanyName); 
    

请参见

概念

准备应用程序以接收数据

将数据获取到应用程序

在 Visual Studio 中将控件绑定到数据

在应用程序中编辑数据

验证数据

保存数据

其他资源

数据集中的关系

Visual Studio 的数据应用程序概述

连接到 Visual Studio 中的数据