简体   繁体   English

如何获取数据表中一行的最后一个单元格?

[英]How do I get the last cell in a row of a DataTable?

    foreach(DataRow row in dt.Rows)
    {
       foreach(var cell in row.ItemArray)
       {
          builder.Append(cell.ToString());
          if(cell != row.lastcell)
             builder.Append("\t");
       }
       builder.Append(Environment.NewLine);
    }

i need to make sure that cell!=the last cell in the row 我需要确保该单元格!=行中的最后一个单元格

how do i do this? 我该怎么做呢?

You don't need to do that. 您不需要这样做。 Just use string.Join instead: 只需使用string.Join代替:

string[] strings = Array.ConvertAll(row.ItemArray, x => x.ToString());
builder.Append(string.Join("\t", strings);

这将为您提供最后一行:

row = (DataRow)table.Rows[table.Rows.Count-1];

You could completely avoid the last cell if you use a for loop: 如果使用for循环,则可以完全避免最后一个单元格:

for (int i=0; i<row.ItemArray-2;i++)
{
    // do your code here, we are taking off the last cell with the -2
}

使用row.ItemArray [row.ItemArray.Length-1]获取最后一个单元格的值

foreach(DataRow row in dt.Rows)
{
   string separator = String.Empty;
   foreach(var cell in row.ItemArray)
   {
      builder.Append(separator);
      builder.Append(cell.ToString());
      separator  = "\t";
   }
   builder.Append(Environment.NewLine);
}

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

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