Search code examples
c#datagrid

summing selected values of datagridview


I using this code for sum selected cells. Its work good but when user selecte cell where is letter is throws exceptions : ) how can i secure when in selectet cells is letters dont make sum

i asked same question but there i cannot add 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["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
            {

            }
        }    

    }

Solution

  • 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
                {
    
                }
            }    
    
        }