对datagridview所选单元格求和时出现问题 [英] Problem when summing datagridview selected cells

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

问题描述

大家好

我标记为(tlblPriceTotal)显示所有选定单元格的总和.

我编写了这段代码

Hi guys

I to label (tlblPriceTotal) show sum of all selected cells.

I programed this code

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
decimal nextNumber = 0;
decimal sumNumbers = 0;
for (int i = 0; i < dataGridView1.SelectedCells.Count - 1; i++)
{
    nextNumber = (decimal)dataGridView1.Rows[i].Cells["priceDataGridViewTextBoxColumn"].Value;
    sumNumbers += nextNumber;
}
tlblPriceTotal.Text = "Sum: " + sumNumbers.ToString();
tlblSelectedCellsTotal.Text = "Total Selected: " + dataGridView1.SelectedCells.Count.ToString();
}


但是它不能正常工作.当我选择某些内容时,此代码将从第一行开始求和
如果我选择另一列,则总和相同(priceDataGridViewTextBoxColumn)
有什么问题可以帮助我吗?
谢谢.


But it does not works correctly. when i selecte something this code begin summing from first row
if i select another column it summing same (priceDataGridViewTextBoxColumn)
what is problem can anybody help me?
Thanks.

推荐答案

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            decimal nextNumber = 0;
            decimal sumNumbers = 0;

            for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
            {
                try
                {
                    nextNumber = Convert.ToDecimal(dataGridView1.SelectedCells[i].Value.ToString());
                    sumNumbers += nextNumber;
                }
                catch (Exception)
                {
                    //throw;
                }
            }
            tlblPriceTotal.Text = "Sum: " + sumNumbers.ToString();
            tlblSelectedCellsTotal.Text = "Total Selected: " + dataGridView1.SelectedCells.Count.ToString();
 }


问题是您的循环在选定的单元格上,但总和在行上.尽管我不确定您要做什么,但是尝试像这样更改循环的内部部分:

The problem is that your loop is on selected cells but your sum is on rows. Although I am not sure what you are trying to do, try changing the inner part of your loop like this:

if (dataGridView1.SelectedCells[i].ColumnIndex == indexofPriceDataGridViewTextBoxColumn)
{
    nextNumber = (decimal)dataGridView1.SelectedCells[i].Value;
}
else
{
    nextNumber = 0;
}


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

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