Click here to Skip to main content
16,016,712 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I want to add column wise data present in Datagridview. I am getting the sum if all values present in cells.

If in a cell value is not there(NULL) it is showing ERROR:
operator + is not defined for type Integer and type DBNull.

Code snippet:
VB
For j As Integer = 0 To DataGridView1.Columns.Count - 1
    For i As Integer = 0 To DataGridView1.Rows.Count - 1
        total = total + DataGridView1(j, i).Value
    Next

    TableLayoutPanel1.Controls(j).Text = total
    total = 0
Next
Posted
Updated 20-May-11 0:27am
v2

+ operator does not work with null so put a simple check before adding the data as follow
VB
For j As Integer = 0 To DataGridView1.Columns.Count - 1
    For i As Integer = 0 To DataGridView1.Rows.Count - 1
        if IsDBNull(DataGridView1(j, i).Value) <> True then
             total = total + DataGridView1(j, i).Value
        end if
    Next

    TableLayoutPanel1.Controls(j).Text = total
    total = 0
Next
 
Share this answer
 
v2
Comments
Member 7940184 20-May-11 7:06am    
ThankU
The reason for this is that null values from the database are represented with DbNull[^] values in memory. You need to add a conditional around the place where you add DataGridView1(j, i).Value to the total, deciding what to do when you see a null value (for example, skip it). There is an example at the above link showing you how to do it.
 
Share this answer
 
try This
total = total + If(IsDBNull(Me.DataGridView1.Item(j, i).Value), 0, Me.DataGridView1.Item(j, i).Value)
 
Share this answer
 

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