汇总datagridview的选定值

时间:2010-12-06 07:44:47

标签: c# datagrid

我将此代码用于总和所选单元格。它的工作很好但是当用户选择单元格在哪里是字母时抛出异常:)我怎样才能在选择单元格中保证字母不要求和

我问了同样的问题,但我无法添加我的代码

 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["cLoadName"]))
            {
                float nextNumber = 0;
                float sumNumbers = 0;

                                        nextNumber = float.Parse(dataGridView1.SelectedCells[i].FormattedValue.ToString());
                    sumNumbers += nextNumber;


                tsslSumSelected.Text = "ჯამი: " + sumNumbers;
                tsslTotalSelected.Text = "მონიშნული: " + dataGridView1.SelectedCells.Count.ToString();
            }
            else
            {

            }
        }    

    }

2 个答案:

答案 0 :(得分:2)

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["cLoadName"]))
            {
                float nextNumber = 0;
                float sumNumbers = 0;

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


                tsslSumSelected.Text = "ჯამი: " + sumNumbers;
                tsslTotalSelected.Text = "მონიშნული: " + dataGridView1.SelectedCells.Count.ToString();
            }
            else
            {

            }
        }    

    }

答案 1 :(得分:0)

public void ComputeGridTot()
{
    try
    {
        decimal qty= 0;
        decimal price = 0;
        decimal tax = 0;
        decimal Total = 0;
        for (int i = 0; i < drGrdView1.Rows.Count; i++)
        {
            if (drGrdView1.Rows[i].Cells[7].Value.ToString() == blcnt.ToString())
            {
                qty += Convert.ToDecimal(drGrdView1.Rows[i].Cells[3].Value);
                price += Convert.ToDecimal(drGrdView1.Rows[i].Cells[4].Value);
                tax += Convert.ToDecimal(drGrdView1.Rows[i].Cells[5].Value);
                Total += Convert.ToDecimal(drGrdView1.Rows[i].Cells[6].Value);

             }
        }
        lblGTax.Text = tax.ToString();
        lblGQty.Text = qty.ToString();
        lblGPrice.Text = price.ToString();
        lblGTot.Text = Total.ToString();
    }
    catch
    {
    }
}