Click here to Skip to main content
15,305,754 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm working with a program that I called Ordering System using visual and sql database. I use textboxes to capture required information and transfer to database/datagridview. I have column called Total where this column handled all calculated cost. What I want is for addition of all rows figures under "Total" column and the value displayed in specific textbox that I call "Sum". But I got errors when I click button to display total orders under Total column. Datagridview's columns consists of numbers and texts. e.g. Customer name, Unit Price etc.

Errors1: - "InvalidCastException was handled"
Errors2: - "Conversion from string to type double is not valid"

Please Help!

What I have tried:

Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As system.Eventargs) handles
Dim sum As Decimal = 0
For x=0 To OrderingDataGridView.Rows.Count - 1
If Not IsDBNull(OrderingDataGridView.Rows(x).Cells(13).Value Then sum=sum+ OrderingDataGridView.Rows(x).Cells(13).Value

End Sub
End Class
Updated 2-Dec-21 22:13pm

1 solution

First off, that's pretty poor code: don't use "magic numbers" like ...Cells(13)... as it's far, far too easy to miscount and cause problems - and that may be the source of your problem!
Use column names instead ...Cells("Total")... and they work regardless of the column ordering.

Second, you need to find out exactly what is in your columns: at a guess, Column 13 contains some information which is not numeric, and that means when VB tries to convert it for you it understandably fails, and your app crashes.
So use the debugger to find out what row is involved - the value of x - and what exactly is in the Total column for that row. From there, it should be pretty obvious what the problem is.

Oh, and BTW: don't use the DGV itself to provide row and column data: use the underlying DataSource (DataTable, Collection, whatever) instead as it involves one less "layer of indirection" and means that user changes to your DGV (filters, ordering, blank new rows for them to enter data into, etc.) don't affect your code!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900