Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Frnds,

I have created one Gridview checkbox column.. it have following error pls help me..
Object reference not to an instance of an object in if Statement:


C#
foreach (DataGridViewRow row in dgvScreenDetails.Rows)
           {
               DataGridViewCheckBoxCell chk = row.Cells[2] as DataGridViewCheckBoxCell;
               // number 0 represents the 1st column of dgv!

               if (Convert.ToBoolean(chk.Value) == true)
               {
                   MessageBox.Show("this cell checked");

               }
           }
Posted
Comments
samit kaneriya 25-Feb-14 8:04am    
give your html code

Use the debugger and check, but I think you will find that row.Cells[2] is not a DataGridViewCheckBoxCell - so as returns a null, and you get an error.

Start with the debugger, and look at what type is actually is: that should tell you is you are reading the wrong column, or it's an empty cell, or what - we can't do that because we can't see your screen, we don't have access to you HDD, and we can't read your mind! :laugh:
 
Share this answer
 
Comments
OriginalGriff 25-Feb-14 5:50am    
Sorry? It's probably a language thing, but I don't understand what you are saying.
Can you try again, with different words, or perhaps use Google Translate from your native language?
Paste the code block will check
 
Share this answer
 
C#
DataGridViewCheckBoxCell chk = row.Cells[2] as DataGridViewCheckBoxCell;

The as keyword will return null if the type conversion failed. You need to check if the variable is null before using it in the if statement. The chk variable is null.
 
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