How to: Locate a Specific Row in a DataTable

How to: Locate a Specific Row in a DataTable 

 

Most applications that consume data need to access specific records that satisfy some kind of criteria. In order to find a particular row in a dataset, you can invoke the Find method of the DataRowCollection object. If the primary key exists, then a DataRow object is returned. If the primary key cannot be found, then a null value is returned.

Finding a Row with a Primary Key Value

To find a row in a typed dataset with a primary key value

  • Call the strongly typed FindBy method that uses the table's primary key to locate a row.

    In the following example, the CustomerID column is the primary key of the Customers table, so the generated FindBy method is FindByCustomerID. The example shows how to assign a specific DataRow to a variable using the generated FindBy method.

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

To find a row in an untyped dataset with a primary key value

  • Call the Find method of a DataRowCollection collection, passing the primary key as a parameter.

    The following example shows how to declare a new row called foundRow and assign it the return value of the Find method. If the primary key is found, the contents of column index 1 are displayed in a message box.

    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");
    }

Finding Rows by Column Values

To find rows based on the values in any column

  • Data tables are created with a Select method that returns an array of DataRows based on the expression passed to the Select method. For more information on creating valid expressions, see the "Expression Syntax" section of the page about the Expression property.

    The following example shows how to use the Select method of the DataTable to locate specific rows.

    DataRow[] foundRows;
    foundRows = dataSet1.Tables["Customers"].Select("CompanyName Like 'A%'");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值