如何对datagridview选择的单元格求和 [英] How to sum datagridview selected cell

查看:296
本文介绍了如何对datagridview选择的单元格求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想要像Excel这样的东西。如果我在一列中选择两个或多个单元格,它应该在标签中显示计算出的值。



示例如果我突出显示三个单元格的值(500, 400和200)。标签应该显示我 1100



我的代码在某种程度上可以,但它没有显示所选单元格的总和值。它只显示第一个选中的单元格值。



我的代码:



Hi,
I wanna archieve something like Excel. If i select two or more cells within a column, it should display me the calculated value in a label.

Example if i highlight three cells with the values (500, 400 and 200). The label should display me 1100

My code is somehow okay but it is not displaying the summed value of the selected cells. It only display the first selected cell value.

My code:

private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
  for (int i = 0; i < datagridview1.SelectedCells.Count; i++)
  {
    if (!datagridview1.SelectedCells.Contains(datagridview1.Rows[i].Cells[i]))
    {
      float nextNumber = 0;
      float sumNumbers = 0;

      if (float.TryParse(datagridview1.SelectedCells[i].FormattedValue.ToString(), out nextNumber))
        sumNumbers += nextNumber;

      label13.Text = "selected value: " + sumNumbers;
      label16.Text = "Nr.selected cell: " + datagridview1.SelectedCells.Count.ToString();
    }
    else
    {
      MessageBox.Show("Can't sum");
    }
  }

推荐答案

你应该放置 float sumNumbers = 0; 在你的循环之外。



你应该重新检查你的循环。看起来纠缠不清[/ edit]
You should place your float sumNumbers = 0; outside your loop.

[edit]And you should recheck your loop overall. Looks something tangled[/edit]


这篇关于如何对datagridview选择的单元格求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆