Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know a row index while iterating with foreach?

Tags:

c#

foreach

in the next example how can I know the current row index?

foreach (DataRow temprow in temptable.Rows)
{
//this.text = temprow.INDEX????
}
like image 528
Luiscencio Avatar asked Oct 08 '09 22:10

Luiscencio


3 Answers

int rowIndex = temptable.Rows.IndexOf(temprow);
like image 156
Nick DeVore Avatar answered Nov 16 '22 02:11

Nick DeVore


If you can use Linq, you can do it this way:

foreach (var pair in temptable.Rows.Cast<DataRow>()
                                   .Select((r, i) => new {Row = r, Index = i}))
{
    int index = pair.Index;
    DataRow row = pair.Row;
}
like image 34
adrianbanks Avatar answered Nov 16 '22 04:11

adrianbanks


You have to create one yourself

var i = 0;
foreach (DataRow temprow in temptable.Rows)
{
    this.text = i;
    // etc
    i++;
}

or you can just do a for loop instead.

like image 22
Joseph Avatar answered Nov 16 '22 02:11

Joseph