Click here to Skip to main content
15,910,661 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have error when i execute code
C#
  foreach (DataGridViewRow row in dataGridView1.Rows)

            {

                dataGridView1.Rows[row.Index].Cells[4].Value = Double.Parse(dataGridView1.Rows[row.Index].Cells[3].Value.ToString())
                    - Double.Parse(dataGridView1.Rows[row.Index].Cells[1].Value.ToString());


            }
<
Posted
Updated 18-Mar-15 23:53pm
v3
Comments
Thanks7872 19-Mar-15 6:04am    
Put breakpoint at the line where you got the error. Debug it and see which one is null. Try to make changes such that it should not be null at that point.

"Object Reference Not Set to an Instance" error says that you are trying to apply any function or any calculation on an object which is null.

In your above case check which one has null. Put a debug point just at the start curly brace of for loop, when you reach there then check in the quick access of below object and you will find which one is null.
C#
dataGridView1.Rows[row.Index].Cells[4]

or
C#
dataGridView1.Rows[row.Index].Cells[3]

or
C#
dataGridView1.Rows[row.Index].Cells[1]
 
Share this answer
 
v2
Comments
Praveen Kumar Upadhyay 19-Mar-15 6:13am    
dataGridView1.Rows[row.Index]
this can also be null. So check this also in quick watch.
[no name] 19-Mar-15 6:17am    
"on an object which is null" -
On a variable/array index that is null (but supposed to reference an object)
Praveen Kumar Upadhyay 19-Mar-15 6:19am    
I did not get your point.
[no name] 19-Mar-15 6:31am    
An object can't be null. A variable can reference an object or be null (or be a value type).
Praveen Kumar Upadhyay 19-Mar-15 6:47am    
An object can be null. If we haven't set the reference to that object, it is null only.
First off, why are you doing that?
If you already have the row, why are you using it's row index to fetch it again, repeatedly?
C#
foreach (DataGridViewRow row in dataGridView1.Rows)
           {
               row.Cells[4].Value = Double.Parse(row.Cells[3].Value.ToString()) - Double.Parse(row.Cells[1].Value.ToString());
           }
is the same, but more readable (and efficient)

Now you need to look at the data and find which of these is null: we can;t do that for you, and the chances are that one or more of your cells contains a null value - so when you do row.Cells[n].Value it tries to call the Value parameter of the non-existent value and you get an exception.

We don't have your data - so we can't tell. So use the debugger, and start looking at what row and column is causing the problem!
 
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