Wednesday, November 19, 2008

Obtaining the largest ID value from a DataTable

In the dotNet Framework data tables are often used to represent tables from a database. And in these there's often an "ID" column. A common desire is to obtain the largest ID value in the data table. I did some searching and couldn't find a direct answer. So I experimented and came up with a very simple solution:

public static int GetMaxID(DataTable dataTable)
// Sort the DataRow Array by descending ID
DataRow[] sortedRows = dataTable.Select(null, "ID DESC");

// and return the first ID, which will be the maximum
return (int)sortedRows[0]["ID"];

No comments:

Post a Comment