Finding DataRowView Objects in a DataView
You can find the index of a DataRowView in a DataView using the Find() method of a
DataView. You can also get an array of DataRowView objects using the FindRows()
method of a DataView. You'll learn how to use the Find() and FindRows() methods in
this section.
Finding the Index of a DataRowView Using the Find() Method
The Find() method returns the index of the DataRowView with the specified primary key
in your DataView. The int returned by this method is the index of the DataRowView if
found; otherwise -1 is returned.
To find the correct index, you must first set the Sort property of your DataView to sort on
the primary key. For example, if you want to find a DataRowView based on the
CustomerID, you must set the Sort property of your DataView to CustomerID,
CustomerID ASC, or CustomerID DESC:
string sortExpression = "CustomerID";
customersDV.Sort = sortExpression;
Assume that the sorted DataRowView objects in customersDV are as follows:
AROUT
Around the Horn
UK
BSBEV
B's Beverages
UK
CONSH
Consolidated Holdings
UK
EASTC
Eastern Connection
customersDV.Sort = sortExpression;
The following example calls the FindRows() method to find the DataRowView that has
the CustomerID of BSBEV:
DataRowView[] customersDRVs = customersDV.FindRows("BSBEV");
Since there is only one match, the customersDRVs array will contain one DataRowView.
Listing 13.2
shows a program that uses the Find() and FindRows() methods.
Listing 13.2: FINDINGDATAROWVIEWS.CS
/*
FindingDataRowViews.cs illustrates the use of the Find() and
FindRows() methods of a DataView to find DataRowView objects
*/
using System;
using System.Data;
using System.Data.SqlClient;
class FindingDataRowViews
{
public static void Main()
{
SqlConnection mySqlConnection =
new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa"
);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =
"SELECT CustomerID, CompanyName, Country " +
"FROM Customers";
// use the Find() method of customersDV to find the index of
// the DataRowView whose CustomerID is BSBEV
int index = customersDV.Find("BSBEV");
Console.WriteLine("BSBEV found at index " + index + "\n");
// use the FindRows() method of customersDV to find the DataRowView
// whose CustomerID is BSBEV
DataRowView[] customersDRVs = customersDV.FindRows("BSBEV");
foreach (DataRowView myDataRowView in customersDRVs)
{
for (int count = 0; count < customersDV.Table.Columns.Count; count++)
{
Console.WriteLine(myDataRowView[count]);
}
Console.WriteLine("");
}
}
}
Tip If you are using an early version of the .NET SDK, you might encounter the
following compilation error when compiling this program:
FindingDataRowViews.cs(59,35): error CS0117: 'System.Data.DataView' does not
contain a definition for 'FindRows'
If you get this error, compile the program with Visual Studio .NET.
The output from this program is as follows:
AROUT
Around the Horn
UK
BSBEV