How to get the row number from a datatable?

2020-02-02 11:50发布

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# datatable
7条回答
放我归山
2楼-- · 2020-02-02 11:56

Try:

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

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-02 12:01

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];
}
查看更多
▲ chillily
4楼-- · 2020-02-02 12:07

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++;
} 
查看更多
SAY GOODBYE
5楼-- · 2020-02-02 12:09
int index = dt.Rows.IndexOf(row);

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

查看更多
我只想做你的唯一
6楼-- · 2020-02-02 12:10

Why don't you try this

for(int i=0; i < dt.Rows.Count; i++)
{
  // u can use here the i
}
查看更多
淡お忘
7楼-- · 2020-02-02 12:10
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);

}
查看更多
登录 后发表回答