DataTable中当前DataRow的索引

时间:2021-12-15 20:31:23
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's something like

在上面的代码中,我还需要包含行索引,以便它就像

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

How can I achieve this?

我怎样才能做到这一点?

P.S. data is not a DataTable but a generic list of myDAL.UsersRow

附: data不是DataTable,而是myDAL.UsersRow的通用列表

2 个解决方案

#1


4  

If data is a List<myDAL.UsersRow> as you suggest, you can use a "for" loop rather than a "for each" loop:

如果数据是您建议的List ,则可以使用“for”循环而不是“for each”循环:

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

If, however, you're implying that your "data" list is not in the same order as the original DataTable's rows, you might be able to use the DataRowCollection.IndexOf method to locate the row in the original table:

但是,如果您暗示您的“数据”列表与原始DataTable的行的顺序不同,则可以使用DataRowCollection.IndexOf方法在原始表中找到该行:

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

#2


1  

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

在ForEach循环之前声明一个计数器变量,并在其中增加它。

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

#1


4  

If data is a List<myDAL.UsersRow> as you suggest, you can use a "for" loop rather than a "for each" loop:

如果数据是您建议的List ,则可以使用“for”循环而不是“for each”循环:

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

If, however, you're implying that your "data" list is not in the same order as the original DataTable's rows, you might be able to use the DataRowCollection.IndexOf method to locate the row in the original table:

但是,如果您暗示您的“数据”列表与原始DataTable的行的顺序不同,则可以使用DataRowCollection.IndexOf方法在原始表中找到该行:

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

#2


1  

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

在ForEach循环之前声明一个计数器变量,并在其中增加它。

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