March 2008
Intermediate to advanced
982 pages
22h 43m
English
You need to find rows meeting certain criteria in a DataTable or DataView.
Choose from the three techniques shown in the solution to find data in the table meeting user-specified criteria.
The solution creates a DataTable containing data from the Person.Contact table in AdventureWorks. The solution uses three different techniques—the DataRowCollection.Find() method, the DataView.Find() method, and the DataView.FindRows() method—to find rows.
The C# code in Program.cs in project FindRows is shown in Example 4-4.
Example 4-4. File: Program.cs for FindRows solution
using System;
using System.Data;
using System.Data.SqlClient;
namespace FindRows
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = "Data Source=(local);" +
"Integrated security=SSPI;Initial Catalog=AdventureWorks;";
string sqlSelect = "SELECT * FROM Person.Contact";
// Fill the DataTable with schema and data
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.FillSchema(dt, SchemaType.Source);
da.Fill(dt);
// Find a row matching a primary key (ContactID) value (429)
Console.WriteLine("---Finding rows using DataTable.Rows.Find()---"); DataRow row = dt.Rows.Find(new object[] { 429 }); if (row != null) Console.WriteLine("{0}\t{1}, {2}", row["ContactID"], row["LastName"], row["FirstName"]); else Console.WriteLine("Row not found."); Console.WriteLine(); DataView dv = dt.DefaultView; // Find a ...Read now
Unlock full access