将float数据类型列转换为double时出错

时间:2014-02-14 13:35:02

标签: c#

下面的代码给出错误:指定的演员无效。

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"));**
        }
    }     

虽然以下代码适合我。但我无法处理以下代码中的NULL

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

请帮助..

3 个答案:

答案 0 :(得分:1)

尝试使用

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

答案 1 :(得分:0)

最后,我必须使用System.DBNull.Value检查

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

答案 2 :(得分:0)

尝试将它们分成多行以避免破坏得墨忒耳法则。它会使阅读更容易。

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