Index of the current DataRow in the DataTable

For Each dr As myDAL.UsersRow In data
   str.AppendLine(dr.UserName)
Next

      

In the above code, I also need to include the row index so that it is something like

str.AppendLine(dr.IndexNumber & " " & dr.UserName)

      

How can I achieve this?

PS is data

not DataTable

, but is a general listmyDAL.UsersRow

0


a source to share


2 answers


If the data is List<myDAL.UsersRow>

as you suggest, you can use a "for" loop rather than a "for each" loop:

for i = 0 to data.Count - 1
    str.AppendLine(i & " " & data[i].UserName)
next

      



If, however, you assume that your list of "data" is not in the same order as the original DataTable rows, you can use DataRowCollection.IndexOf to find the row in the original table:

for each dr as myDAL.UsersRow in data
    str.AppendLine(dr.Table.Rows.IndexOf(dr) & " " & dr.UserName)
next

      

+4


a source


Declare a counter variable before the ForEach loop and increment it internally.



    Dim counter As Integer = 0
    For Each dr As myDAL.UsersRow In data
        counter = counter + 1
        str.AppendLine(counter.ToString() & " " & dr.UserName)
    Next

      

+1


a source







All Articles