Find row in datatable with specific id

RSM picture RSM · Dec 17, 2013 · Viewed 203.1k times · Source

I have two columns in a datatable:

ID, Calls. 

How do I find what the value of Calls is where ID = 5?

5 could be anynumber, its just for example. Each row has a unique ID.

Answer

Karl Anderson picture Karl Anderson · Dec 17, 2013

Make a string criteria to search for, like this:

string searchExpression = "ID = 5"

Then use the .Select() method of the DataTable object, like this:

DataRow[] foundRows = YourDataTable.Select(searchExpression);

Now you can loop through the results, like this:

int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
    // Get value of Calls here
    result = Int32.TryParse(dr["Calls"], out numberOfCalls);

    // Optionally, you can check the result of the attempted try parse here
    // and do something if you wish
    if(result)
    {
        // Try parse to 32-bit integer worked

    }
    else
    {
        // Try parse to 32-bit integer failed

    }
}