SSOPLIF
SSOPLIF

Reputation: 321

Unable to convert object to double

When inserting a new student into the database, their GPA is not entered, so when I call an event handler to display the GPA, it crashes.

object value;    
sql = string.Format("SELECT ROUND(AVG(CAST(Rating AS Float)), 4) FROM GPA WHERE StudentID={0};;", StudentID);
value = this.datatier.ExecuteScalarQuery(sql);

double avgGPA;
if (value != null)
{
    System.Windows.Forms.MessageBox.Show("null");
    avgGPA = Convert.ToDouble(value);
}
else avgGPA = 0.0;

I tried this fix, where I make sure value!=null before I Convert.ToDouble(), but I am crashing regardless, particularly on this line:

avgGPA = Convert.ToDouble(value);

with error: Object cannot be cast from DBNull to other types.

My question is how do I assign a default value, like 0.0, so that the program doesn't crash when a GPA isn't found?

EDIT: Everyone was spot on on the solution, thanks to all! The new question becomes, is DBNull always the null of a database query?

Upvotes: 4

Views: 2701

Answers (4)

evilone
evilone

Reputation: 22740

You can try:

double avgGPA = Convert.IsDBNull(value) ? 0.0 : Convert.ToDouble(value);

Upvotes: 1

Joe Enos
Joe Enos

Reputation: 40413

You can do it on either side, whichever makes the most sense given your circumstance:

-- In the query, return zero if null
select isnull(ROUND(AVG(CAST(Rating AS Float)), 4), 0.0) from...

Or

// In the code, check for DBNull
if (value != DBNull.Value)
{
    avgGPA = Convert.ToDouble(value);
}

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

In query check if null return default value using isnull():

SELECT ROUND(AVG(CAST(isnull(Rating,0) AS Float)), 4)

Upvotes: 1

Perfect28
Perfect28

Reputation: 11327

Just check if it's DBNull

avgGPA = value == DBNull.Value ? 0D : Convert.ToDouble(value);

Upvotes: 3

Related Questions