Click here to Skip to main content
15,881,638 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
dataGridView.Rows[e.RowIndex].Cells["ReturnQty"].Value.ToString()

If the current cell value is null it shows the NullReferenceException error:
I want to do
C#
if(!String.IsNullOrEmpty(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
{

       // do sonmthing
}
Posted
Updated 17-Feb-11 23:23pm
v3

Try something like:
C#
if(MainGridView.Rows.Count >0 && MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] != null)
{
   if(!String.IsNullOrEmpty(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
   {
       // do sonmthind
   }
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 18-Feb-11 12:06pm    
All right, 5.
--SA
Hi,

instead of using .tostring()
use Convert.tostring() as it handles null values
u can write like

if(Convert.Tostring(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value)){       // do sonmthing}


Hope it helps..........
:-O
 
Share this answer
 
Comments
Ashishmau 18-Feb-11 5:50am    
Atleast Vote yaar,,if problem solves
Manas Bhardwaj 18-Feb-11 5:59am    
have my 5...happy?
Member 10602680 2-Jun-14 5:52am    
Thanx........It works
Sergey Alexandrovich Kryukov 18-Feb-11 12:06pm    
All right, 5.
--SA
Member 8011155 12-Dec-11 3:46am    
System.NullReferenceException: Object reference not set to an instance of an object.
In addition to Sandeep's answer, I would add e.RowIndex >= 0 && e.ColumnIndex >= 0 inside if.
And IsNullOrEmpty only takes a string as parameter, but Cell.Value property is of type Object. So you can't pass it directly to the IsNullOrEmpty method.

Try th something like this:
C#
if (MainGridView.Rows.Count > 0 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
   DataGridViewCell cell = MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
   if (cell != null && !String.IsNullOrEmpty(cell.Value as string))
   {
       // do something
   }
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 18-Feb-11 12:06pm    
All right, 5.
--SA

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