繁体   English   中英

如何从数据表中获取行号?

[英]How to get the row number from a datatable?

我循环遍历数据表中的每一行:

foreach (DataRow row in dt.Rows) {}

我想得到dt datatable中当前行的索引。 例如:

int index = dt.Rows[current row number]

我该怎么做呢?

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

但你可能最好使用for循环而不是foreach。

如果你需要你正在使用的项目的索引,那么使用foreach循环是迭代集合的错误方法。 更改循环方式,以便获得索引:

for(int i = 0; i < dt.Rows.Count; i++)
{
    // your index is in i
    var row = dt.Rows[i];
}

你为什么不试试呢?

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

你有两个选择。

  1. 您可以创建自己的索引计数器并递增它
  2. 您可以使用for循环,而不是使用foreach循环

单个行只表示数据,因此它不知道它所在的行。

你知道DataRow是DataTable的行吗?

您目前已经遍布每一行。 您只需跟踪有多少行以获取当前行。

int i = 0;
int index = 0;
foreach (DataRow row in dt.Rows) 
{
index = i;
// do stuff
i++;
} 
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);

}

尝试:

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

我认为它是最短的,因此也是最简单的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM