对于Double Data Type,无法将对象从DBNull强制转换为其他类型

时间:2013-11-14 10:47:54

标签: c# asp.net

当数据库中的任何单元格中存在空值时,我看到错误,无法将对象从DBNull转换为其他类型。 - Asp.net网格视图

<asp:TemplateField ItemStyle-Width="120" HeaderText="Price Difference">
                                     <ItemTemplate>
<%# PercentageChange(DataBinder.Eval(Container.DataItem, "FirstPrice"),DataBinder.Eval(Container.DataItem, "SecondPrice")) %>

                                     </ItemTemplate>
                                 </asp:TemplateField>

C#

protected string PercentageChange(object client_Price, object second_price)
    {
       double price1 = Convert.ToDouble(client_Price);
            double price2 = Convert.ToDouble(second_price);
            double percentagechange = ((price1 - price2) / price2) * 100;
             return percentagechange ;
} 

3 个答案:

答案 0 :(得分:3)

您需要将您的值与DBNull.Value进行比较,如下所示

protected string PercentageChange(object client_Price, object second_price)
{
       if(client_price==DBNull.Value)
       {
           .....
       }
       //double price1 = Convert.ToDouble(client_Price);
       //double price2 = Convert.ToDouble(second_price);
       //double percentagechange = ((price1 - price2) / price2) * 100;
       //return percentagechange ;
 } 

答案 1 :(得分:2)

然后检查它是DBNull还是null:

protected string PercentageChange(object client_Price, object second_price)
{
    if(DBNull.Value.Equals(client_Price) || client_Price == null || DBNull.Value.Equals(second_price) || second_price == null)
        return "N/A"; // or whatever

    double price1 = Convert.ToDouble(client_Price);
    double price2 = Convert.ToDouble(second_price);
    double percentagechange = ((price1 - price2) / price2) * 100;
    return percentagechange.ToString();
} 

答案 2 :(得分:0)

错误原因:  在面向对象的编程语言中,null表示缺少对对象的引用。 DBNull表示未初始化的变体或不存在的数据库列。 源:MSDN

我遇到的实际代码错误:

在更改代码之前:

        if( ds.Tables[0].Rows[0][0] == null ) //   Which is not working

         {
                seqno  = 1; 
          }
        else
        {
              seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
         }

更改代码后:

   if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
        {
                    seqno  = 1; 
         }
            else
            {
                  seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
             }

<强>结论: 当数据库值返回null值时,我们建议使用DBNull类,而不是像C#语言一样指定为null。