Keven Diuliy
Keven Diuliy

Reputation: 131

Retrieve specific datarow in C# Datatable

I have a datatable in C# called "table" that looks like the following:.

 ID   Value
 10    A
 20    B
 30    C

(It really has about 1200 rows, but I tried to simplify it) My goal is to be able to print specific rows in this datatable. For example, if I would like to print the second row (row index 1) I would use the following:

Response.Write(table.Rows[1]["Value"].ToString());

This prints out the value "B" which is what I want, but is there a way to use the "ID" column to print that specific value instead of using the row index of 1. I would like to be able to link ID 10 and Value B together somehow.

Upvotes: 0

Views: 4392

Answers (3)

System Down
System Down

Reputation: 6260

If ID isn't setup as a PK (or you want to query another field), you could use a Linq query

var chosenRow = (from row in table.AsEnumerable()
                    where row.Field<int>("ID") == 10
                    select row).First();

chosenRow is the first DataRow object that meets the criteria set in the where clause. So you could just:

Response.Write(chosenRow["Value"].ToString());

Upvotes: 0

Pellizon
Pellizon

Reputation: 1375

you can loop trough your datatable using for each, and when the ID equals 10, then you do what you want

would be something like this:

for each row as datarow in datatable.rows
   if row.Items["ID"] = 10 Then
    //do something
   end if

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

If ID is defined as the primary key, this should look up B by its ID key:

Response.Write(table.Rows.Find(20).["Value"].ToString());

Upvotes: 2

Related Questions