Click here to Skip to main content
14,775,044 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am using following code for sum of grid view column.
Dim a, b, c As Decimal
        For i = 0 To GridItem.Rows.Count
            a = Convert.ToDecimal(GridItem.Rows(i).Cells(7).Value.ToString())
            c = c + a
        Next
        
        txtBasic.Text = c

System throws an error:Object reference not set to an instance of an object.
after debug the code I understand the problem.I add 2 rows in grid view.
Problem is system shows Gridview1.Rows.Count=3.
as per count for loop iterate 3 times 3rd time system throws an error:Object reference not set to an instance of an object.

1st time I entered =500.2nd time=2000.at second iteration of for loop value of c=2500.
Posted
Updated 9-Jan-13 4:16am
v2

Whenever you work with an object hierarchy, you should always perform an existence check before attempting to drill down. That way you eliminate issues like what you are encountering here.
For example.
Dim a, b, c As Decimal
For i = 0 to GridItem.Rows.Count
If !IsNothing(GridItem.Rows(i)) And !IsNothing(GridItem.Rows(i).Cells(7) Then
   If Decimal.TryParse( GridItem.Rows(i).Cells(7).Value, out a ) Then
      c = c + a
   End If
End If
txtBasic.Text = c.ToString()
   
v2
Comments
Sandeep Mewara 9-Jan-13 9:38am
   
5!
Entire solution is given over here regarding your problem :
http://csharpdotnetfreak.blogspot.com/2009/07/display-total-in-gridview-footer.html[^]
   
For i = 0 To GridItem.Rows.Count - 1
   

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