Object cannot be cast from DBNull to other types for Double Data Type

后端 未结 3 503
暗喜
暗喜 2021-01-27 06:39

I am seeing error when there is null value in database for any cell, Object cannot be cast from DBNull to other types. - Asp.net grid view



        
相关标签:
3条回答
  • 2021-01-27 06:50

    You need to compare you values with DBNull.Value as follow

    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 ;
     } 
    
    0 讨论(0)
  • 2021-01-27 06:52

    Then check if it's DBNull or 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();
    } 
    
    0 讨论(0)
  • 2021-01-27 07:02

    Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN

    Actual Code which I faced error:

    Before changed the code:

            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;
             }
    

    After changed the code:

       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;
                 }
    

    Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.

    0 讨论(0)
提交回复
热议问题