Finding a row in a DataTable

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.

About Rob

I've been interested in computing since the day my Dad purchased his first business PC (an Amstrad PC 1640 for anyone interested) which introduced me to MS-DOS batch programming and BASIC.

My skillset has matured somewhat since then, which you'll probably see from the posts here. You can read a bit more about me on the about page of the site, or check out some of the other posts on my areas of interest.

No Comments

Add a Comment