Share via


如何:定位数据表中的特定行

更新:2007 年 11 月

大多数使用数据的应用程序需要访问满足某种条件的特定记录。为了找到数据集中的特定行,可调用 DataRowCollection 对象的 Find 方法。如果存在主键,将返回 DataRow 对象。如果找不到主键,则返回空值。

查找具有主键值的行

在类型化的数据集中查找具有主键值的行

  • 调用使用表的主键来定位行的强类型 FindBy 方法。

    在下面的示例中,CustomerID 列是 Customers 表的主键,因此生成的 FindBy 方法为 FindByCustomerID。此示例演示如何使用生成的 FindBy 方法将特定的 DataRow 赋给变量。

    Dim customersRow As NorthwindDataSet.CustomersRow
    customersRow = NorthwindDataSet1.Customers.FindByCustomerID("ALFKI")
    
    NorthwindDataSet.CustomersRow customersRow = 
        northwindDataSet1.Customers.FindByCustomerID("ALFKI");
    

在非类型化的数据集中查找具有主键值的行

  • 调用 DataRowCollection 集合的 Find 方法,同时将主键作为参数传递给它。

    下面的示例演示如何声明新行(名为 foundRow)并将 Find 方法的返回值分配给它。如果找到主键,消息框中将显示列索引 1 的内容。

    Dim s As String = "primaryKeyValue"
    Dim foundRow As DataRow = DataSet1.Tables("AnyTable").Rows.Find(s)
    
    If foundRow IsNot Nothing Then
        MsgBox(foundRow(1).ToString())
    Else
        MsgBox("A row with the primary key of " & s & " could not be found")
    End If
    
    string s = "primaryKeyValue";
    DataRow foundRow = dataSet1.Tables["AnyTable"].Rows.Find(s);
    
    if (foundRow != null) 
    {
        MessageBox.Show(foundRow[1].ToString());
    }
    else
    {
        MessageBox.Show("A row with the primary key of " + s + " could not be found");
    }
    

通过列值查找行

基于任意列中的值查找行

  • 使用 Select 方法创建数据表,Select 方法基于传递给它的表达式返回 DataRow 数组。有关创建有效表达式的更多信息,请参见关于 Expression 属性的页的“表达式语法”部分。

    下面的示例演示如何使用 DataTableSelect 方法来定位特定行。

    Dim foundRows() As Data.DataRow
    foundRows = DataSet1.Tables("Customers").Select("CompanyName Like 'A%'")
    
    DataRow[] foundRows;
    foundRows = dataSet1.Tables["Customers"].Select("CompanyName Like 'A%'");
    

请参见

参考

Find

Select

其他资源

在应用程序中编辑数据

连接到 Visual Studio 中的数据

准备应用程序以接收数据

将数据获取到应用程序

在 Windows 应用程序中的窗体上显示数据

在应用程序中编辑数据

验证数据

保存数据