Interstellar
Interstellar

Reputation: 674

Error while converting float datatype column to double

Below code gives error: Specified cast is not valid.

protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           DataRow row = ((DataRowView)e.Row.DataItem).Row;
           **double Yellow = Convert.ToDouble(row.Field<float?>("Yellow"));**
        }
    }     

While below code works for me. But I'm unable to handle NULL values in below code

double Yellow = Convert.ToDouble(((DataRowView)e.Row.DataItem)["Yellow"]);

Please help..

Upvotes: 0

Views: 309

Answers (3)

Carbine
Carbine

Reputation: 7903

Try to break them into multiple lines to avoid breaking Law of Demeter. It would make it easier to read.

var dataRowView = e.Row.DataItem as DataRowView;
DataRow row = dataRowView.Row;
var result = ( row["Yellow"] as double? ) ?? 0.0; 

Upvotes: 0

Interstellar
Interstellar

Reputation: 674

Finally, I had to use System.DBNull.Value check

if (((DataRowView)e.Row.DataItem)["Yellow"] != System.DBNull.Value)
            {
               double? Yellow =
                    (double?)Convert.ToDouble(((DataRowView)e.Row.DataItem)["Yellow"]);
            }

Upvotes: 0

melvas
melvas

Reputation: 2356

try to use

double? Yellow = ((DataRowView)e.Row.DataItem)["Yellow"] != null ? Convert.ToDouble(((DataRowView)e.Row.DataItem)["Yellow"]) : (double?)null;

Upvotes: 1

Related Questions