How to get the row number from a datatable?

前端 未结 7 1424
谎友^
谎友^ 2020-12-08 06:18

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

相关标签:
7条回答
  • 2020-12-08 06:48

    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++;
    } 
    
    0 讨论(0)
  • 2020-12-08 06:53
    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);
    
    }
    
    0 讨论(0)
  • 2020-12-08 07:01
    int index = dt.Rows.IndexOf(row);
    

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

    0 讨论(0)
  • 2020-12-08 07:04

    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];
    }
    
    0 讨论(0)
  • 2020-12-08 07:06

    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.

    0 讨论(0)
  • 2020-12-08 07:08

    Why don't you try this

    for(int i=0; i < dt.Rows.Count; i++)
    {
      // u can use here the i
    }
    
    0 讨论(0)
提交回复
热议问题