Ksice
Ksice

Reputation: 3327

Get the row next to the row got with DataTable.Select()

I have DataTable object with next data:

Id Value
1   val1
3   val2
2   val3

I'm selecting one row next way:

 table.Select("Id=1");

This query gives me row

 1 val1

And next I want to take the row next to selected one, i.e. row

 3 val2

Can I do this somehow? Is it possible? Maybe there is something like row's position in a table, that I can use to select next row by incrementing this value?

Upvotes: 2

Views: 9697

Answers (1)

Baz1nga
Baz1nga

Reputation: 15579

DataTable.Rows.IndexOf() is the only thing that I can think of.

How:

var rows=table.Select("Id=1");
var indexOfRow=table.Rows.IndexOf(rows[0]); //since Id only 1 match

var nextRow=table.Rows[indexOfRow+1];

Example:

    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof (int));
    dt.Columns.Add("AnotherID", typeof(int));
    dt.Columns.Add("Content", typeof(string));
    dt.PrimaryKey = new[] {dt.Columns["ID"]};

    // Add some data
    dt.Rows.Add(1, 10, "1");
    dt.Rows.Add(2, 11, "2");
    dt.Rows.Add(3, 12, "3");
    dt.Rows.Add(4, 13, "4");

    var index = dt.Rows.IndexOf(dt.Rows.Find(3));

    // index is 2

    Console.WriteLine(dt.Rows[index+1]);

Output in Linqpad

DataRow
ID 4
AnotherID 13
Content 4

Hope that helps

Upvotes: 5

Related Questions