Finding a row in a DataTable

| | Comments (0)
If you have a System.Data.DataTable that contains the columns {ItemId, ItemName, ItemQuantity} and wanted to find the record for a given ItemId, you could always use the followind code:

int ItemIdToFind = 32;
DataRow foundRow = null;
foreach(DataRow row in ItemsTable.Rows)
{
  if (Convert.ToInt32(row["ItemId"]) == ItemIdToFind)
  {
    foundRow = row;
    break;
  }
}

Alternatively, you could make use of the Find method on the DataRow, by writing:

int ItemIdToFind = 32;
itemsTable.PrimaryKey = new DataColumn[] { itemsTable.Columns["ItemId"] };
DataRow foundRow = itemsTable.Rows.Find(ItemIdToFind);
Not only is the second example a lot shorter, but it uses the implementation inside of the DataRow class which is not only likely to be quicker (may not be), but is also more likely to be correct.

Leave a comment

About this Entry

This page contains a single entry by Rob published on March 26, 2009 8:30 AM.

The blogs.msdn.com/JScript blog was the previous entry in this blog.

Coolite - "breaks" the IE7/8 X-UA-Compatible meta-tag is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.02