Click here to Skip to main content
15,902,911 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am creating windows application using datagridview, I am getting error from cell values binding time.

C#
meters += Convert.ToDecimal(dataGridView1.Rows[i].Cells[1].Value);


What I have tried:

C#
Object cannot be cast from DBNull to other types.
Posted
Updated 23-Oct-16 6:56am

You cannot convert a DbNull to anything else.

The solution is very simple. Check for DbNull before you try to convert the value to a decimal.

var value = dataGridView1.Rows[i].Cells[1].Value;
if (value != DbNull.Value)
{
    meters += Convert.ToDecimal(value);
}
 
Share this answer
 
Comments
Boopalslm 23-Oct-16 13:05pm    
sir it's working good, thanks a lot.
Karthik_Mahalingam 27-Oct-16 2:50am    
if it works, please close this post by marking it as answer.
Yes, that error is absolutely correct. If the database has a null in it, the value returned is DbNull.Value. You have to check for it if there is the slightest possibility that one your values coming from the database has a null.

I wrote a small article a short time ago that has some helper extensions that DO check for DBNull. Take a look at the link below - they may help you.

Coping with DBNull[^]
 
Share this answer
 
apparently that record has a null value. database null get converted to a
C#
DBNull.Value
. You need to cast to a nullable decimal and then add it to your variable

C#
var d = (decimal?) dataGridView1.Rows[i].Cells[1]; 
meters += d.GetValueOrDefault(); // can do this
// or can do this too
if(d.HasValue){
    meters += d.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