Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the row number from a datatable?

Tags:

c#

datatable

I am looping through every row in a datatable:

foreach (DataRow row in dt.Rows) {} 

I would like to get the index of the current row within the dt datatable. for example:

int index = dt.Rows[current row number] 

How do i do this?

like image 702
JOE SKEET Avatar asked Dec 21 '10 19:12

JOE SKEET


People also ask

What is a row index?

The rowIndex property returns the position of a row in the rows collection of a table.

How do I get row numbers in R?

To Generate Row number to the dataframe in R we will be using seq.int() function. Seq.int() function along with nrow() is used to generate row number to the dataframe in R. We can also use row_number() function to generate row index.

What is fnRowCallback?

For each row that is generated for display, the fnRowCallback() function is called. It is passed the row node which can then be modified.


2 Answers

int index = dt.Rows.IndexOf(row); 

But you're probably better off using a for loop instead of foreach.

like image 117
Jamie Ide Avatar answered Sep 20 '22 22:09

Jamie Ide


If you need the index of the item you're working with then using a foreach loop is the wrong method of iterating over the collection. Change the way you're looping so you have the index:

for(int i = 0; i < dt.Rows.Count; i++) {     // your index is in i     var row = dt.Rows[i]; } 
like image 45
Justin Niessner Avatar answered Sep 21 '22 22:09

Justin Niessner