Click here to Skip to main content
15,909,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
I am retrive the Int value from datagridview to int variable. Some time datagridview row value will be null. at that time it will display
Error (Object cannot be cast from DBNull to other types.
)

Index = Convert.ToInt32(MyGrid.Rows[2].Cells[8].Value);


What I have tried:

I know with below code i can solve this but can you suggest me any other safe way.
if(MyGrid.Rows[2].Cells[8].Value != null)
{
Index = Convert.ToInt32(MyGrid.Rows[2].Cells[8].Value);
}
Posted
Updated 12-May-17 23:27pm

You can't cast a DBNull value to any type: that's what DBNull is saying - it's a special value which says "the database contains no value in this column".
Trying to cast it to an integer is like trying to make this sum work:
x = y +
Y plus what? You don't know, I don't know, and for sure your database doesn't know either! :laugh:

Instead, try this:
C#
object o = MyGrid.Rows[2].Cells[8].Value;
Index = o == DBNull.Value ? 0 : (int) o;
Or replace zero with another default value.
 
Share this answer
 
Comments
AZHAR SAYYAD 13-May-17 5:17am    
Thanks sir satisfy with answer
C#
var index=
    (MyGrid.Rows[2].Cells[8].Value).Equals(null)
    ? 0
    : Convert.ToInt32((MyGrid.Rows[2].Cells[8].Value);

//or try This remove Value from Cell[8]

var index=
    (MyGrid.Rows[2].Cells[8]).Equals(null)
    ? 0
    : Convert.ToInt32((MyGrid.Rows[2].Cells[8].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