Hi,
i want to total the values in column9 in Patientdatagridview to a textbox1.
here is my code but it displayes each value, not the total.
e.g. if values are 200, 200, 200 then it should display 600
but here it says 0200200200

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim tot As String = 0
        For i As Integer = 0 To PatientDetailsDataGridView.RowCount - 1
                       tot += PatientDetailsDataGridView.Rows(i).Cells(8).Value
                    Next
        If tot = 0 Then
            MessageBox.Show("No Records Found")
        End If
        TextBox1.Text = tot.ToString()

    End Sub

Dani AI

Generated

You are seeing concatenation because the cell values are strings. In WinForms, it is safer to sum using Decimal (especially for money) and to parse robustly, skip the new row, and handle nulls/DBNULL. Also remember column indexes are zero-based, so Cells(8) is the 9th column. Avoid Val because it ignores culture and has permissive parsing; use Decimal.TryParse with the current culture instead (Decimal.TryParse) and skip the IsNewRow.

Example loop:

Dim total As Decimal = 0D
For Each row As DataGridViewRow In PatientDetailsDataGridView.Rows
    If row.IsNewRow Then Continue For
    Dim v As Object = row.Cells(8).Value
    If v Is Nothing OrElse v Is DBNull.Value Then Continue For
    Dim n As Decimal
    If Decimal.TryParse(Convert.ToString(v),
                        System.Globalization.NumberStyles.Any,
                        System.Globalization.CultureInfo.CurrentCulture, n) Then
        total += n
    End If
Next
TextBox1.Text = total.ToString("N2")

If the grid is bound to a DataTable, you can let ADO.NET do the math and avoid iterating:

Dim dt = TryCast(PatientDetailsDataGridView.DataSource, DataTable)
If dt IsNot Nothing Then
    Dim sumObj = dt.Compute("SUM([YourColumnName])", Nothing)
    Dim total As Decimal = If(IsDBNull(sumObj), 0D, Convert.ToDecimal(sumObj))
    TextBox1.Text = total.ToString("N2")
End If

References: Convert.ToDecimal, DataTable.Compute, CultureInfo.

Recommended Answers

All 3 Replies

"+" Charactor always concatinates two string type values i.e "200" +"200" always give you the result 200200 instead of 400, because you treat them as string type. If you declare them as numeric type then it will give you 400.

Your mistake is at line no 2. Declare tot as double type instead of string type.

Dim tot As Double = 0#

and the loop should be

For i As Integer = 0 To PatientDetailsDataGridView.RowCount - 1
    tot += Val(PatientDetailsDataGridView.Rows(i).Cells(8).Value)
Next

Hope it should help you.

Yes, I got. Thanks

this one good it help me out thnks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.