locked
Sum of columns value in decimal RRS feed

  • Question

  • Hi

    I have found many discussions about columns sum but my problem is that i try to sum currency and if cell has decimals in it it gives error. any help?

    here is my code

     Dim sum As Double = 0
                For i = 0 To LaskuTuotteetDataGridView.RowCount - 1
                    sum += LaskuTuotteetDataGridView.Rows(i).Cells("DataGridViewTextBoxColumn5").Value
                Next
    
                LaskuYht.Text = sum

    error: Conversion from string "5.2" to type 'Double' is not valid

    thanks :)

    Saturday, April 14, 2012 1:53 PM

Answers

  • The problem is not a conversion from decimal, but a conversion from string to double.  However, the string "5.2" should be convertible to Double.  If you do the conversion yourself you can handle the error that occurs.

                For i = 0 To LaskuTuotteetDataGridView.RowCount - 1
                    Dim D As Double
                    If Not Double.TryParse(
    LaskuTuotteetDataGridView.Rows(i).Cells("DataGridViewTextBoxColumn5").Value, D) Then
                        MsgBox("Error in value at row " & i.ToString)
                   Else
                        sum
    += D
               
    Next
    One reason for the coversion failing is that the decimal point is not the correct character for the current locale.

    Saturday, April 14, 2012 2:04 PM

All replies

  • The problem is not a conversion from decimal, but a conversion from string to double.  However, the string "5.2" should be convertible to Double.  If you do the conversion yourself you can handle the error that occurs.

                For i = 0 To LaskuTuotteetDataGridView.RowCount - 1
                    Dim D As Double
                    If Not Double.TryParse(
    LaskuTuotteetDataGridView.Rows(i).Cells("DataGridViewTextBoxColumn5").Value, D) Then
                        MsgBox("Error in value at row " & i.ToString)
                   Else
                        sum
    += D
               
    Next
    One reason for the coversion failing is that the decimal point is not the correct character for the current locale.

    Saturday, April 14, 2012 2:04 PM
  • Also, you would be better to use the underlying data source instead of the bound grid view.

    Assuming you had a data table named LaskuTuotteetDataTable to which the DataGridView was bound, and TextBoxColumn5 was mapped to a field called "columnName", then you could use code like:

    Dim total As Double = LaskuTuotteetDataTable.Compute("SUM(columnName)", String.Empty)

    The Compute() method allows you to quickly execute TSQL aggregate commands, such as SUM().

    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, April 18, 2012 4:33 PM
    Moderator
  • Got it solved thanks :)
    Saturday, April 21, 2012 2:48 PM