How to get the row number from a datatable?

C#Datatable

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

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

Solution 2 - C#

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];
}

Solution 3 - C#

You have two options here.

  1. You can create your own index counter and increment it
  2. Rather than using a foreach loop, you can use a for loop

The individual row simply represents data, so it will not know what row it is located in.

Solution 4 - C#

Why don't you try this

for(int i=0; i < dt.Rows.Count; i++)
{
  // u can use here the i
}

Solution 5 - C#

You do know that DataRow is the row of a DataTable correct?

What you currently have already loop through each row. You just have to keep track of how many rows there are in order to get the current row.

int i = 0;
int index = 0;
foreach (DataRow row in dt.Rows) 
{
index = i;
// do stuff
i++;
} 

Solution 6 - C#

ArrayList check = new ArrayList();            

for (int i = 0; i < oDS.Tables[0].Rows.Count; i++)
{
    int iValue = Convert.ToInt32(oDS.Tables[0].Rows[i][3].ToString());
    check.Add(iValue);

}

Solution 7 - C#

Try:

int i = Convert.ToInt32(dt.Rows.Count);

I think it's the shortest, thus the simplest way.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJOE SKEETView Question on Stackoverflow
Solution 1 - C#Jamie IdeView Answer on Stackoverflow
Solution 2 - C#Justin NiessnerView Answer on Stackoverflow
Solution 3 - C#Mitchel SellersView Answer on Stackoverflow
Solution 4 - C#namcoView Answer on Stackoverflow
Solution 5 - C#Security HoundView Answer on Stackoverflow
Solution 6 - C#user620755View Answer on Stackoverflow
Solution 7 - C#Vakho AkobiaView Answer on Stackoverflow