Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find row in datatable with specific id

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.

like image 659
RSM Avatar asked Dec 17 '13 15:12

RSM


People also ask

How can I get specific row from DataTable?

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true. and simply call it as shown below; DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);

How to find row index in DataTable?

To find a value in DataTable , use DataTable 's Select() method: DataRow[] rows = dt. Select("Column1 = 'this'"); Once you get the row(s), you can find its index using DataTable.

What is the row selector?

The row selector is a component that acts like a visual filter for datasets. It takes one dataset, chops it up into various ranges based on its configuration, and lets the user choose the splices. Then it creates a virtual dataset that only contains the rows that match the selected splices.


3 Answers

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

    }
}
like image 73
Karl Anderson Avatar answered Oct 17 '22 04:10

Karl Anderson


You can use LINQ to DataSet/DataTable

var rows = dt.AsEnumerable()
               .Where(r=> r.Field<int>("ID") == 5);

Since each row has a unique ID, you should use Single/SingleOrDefault which would throw exception if you get multiple records back.

DataRow dr = dt.AsEnumerable()
               .SingleOrDefault(r=> r.Field<int>("ID") == 5);

(Substitute int for the type of your ID field)

like image 43
Habib Avatar answered Oct 17 '22 04:10

Habib


You can try with method select

DataRow[] rows = table.Select("ID = 7");
like image 11
marcello Avatar answered Oct 17 '22 04:10

marcello