0

我希望累积每个单元格的值并将其显示在弹性单元格网格末尾的“总列”中。解决这个问题的最佳方法是什么?

到目前为止,我有以下代码,但我认为这是不正确的!

int total = 0;
for (int B = 3; B < 27; B++)
{
    total = total + int.Parse(this.grid2.Cell(0, B).ToString());
    this.grid2.Cell(0, 27).Text = total.ToString();
}
4

1 回答 1

0

您的代码对我来说似乎是正确的,但可以改进:

int total = 0;
for (int B = 3; B < 27; B++)
{
      total = total + Convert.ToInt32(this.grid2.Cell(0, B));
}

this.grid2.Cell(0, 27).Text = total.ToString();

只将需要重复的内容放在 for 循环中。如果只需要执行一次,请将其放在循环之后(或可能的话之前)。此外,尝试为变量使用更有意义的名称。如果您不想给它一个长名称,我会将“B”更改为“i”,或者更改为“列”,这样您(和其他开发人员,如我们)就知道它代表什么。

顺便说一句,代码计算一行(第一行)的总和。如果你想对每一行都这样做,那么你将需要一个双 for 循环:

for(int row = 0;row < numRows; row++){
  int total = 0;
    for (int column = 3; column < 27; column++)
    {
          total = total + Convert.ToInt32(this.grid2.Cell(row, column));
    }
  this.grid2.Cell(row, 27).Text = total.ToString();
}
于 2013-05-29T11:14:11.350 回答