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;Alternatively, you could make use of the Find method on the DataRow, by writing:
DataRow foundRow = null;
foreach(DataRow row in ItemsTable.Rows)
{
if (Convert.ToInt32(row["ItemId"]) == ItemIdToFind)
{
foundRow = row;
break;
}
}
int ItemIdToFind = 32;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.
itemsTable.PrimaryKey = new DataColumn[] { itemsTable.Columns["ItemId"] };
DataRow foundRow = itemsTable.Rows.Find(ItemIdToFind);

Leave a comment