0

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

<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 ;
} 
Vikash Rathee
  • 1,776
  • 2
  • 25
  • 43
  • 1
    Oh `DBNull`, how much do I loathe thee? Let me count the ways... http://stackoverflow.com/a/9632050/23354 – Marc Gravell Nov 14 '13 at 10:55
  • I do have another problem, let's say price1 is a property of dbml table, tagged as bit and is placed at column 7 of datagridview.. bool canViewInOut = (dataGridView1.Rows[i].Cells[7].Value == DBNull.Value || !Convert.ToBoolean(dataGridView1.Rows[i].Cells[7].Value)) ? false : true; – Juran Mar 15 '16 at 01:54

3 Answers3

3

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 ;
 } 
शेखर
  • 17,412
  • 13
  • 61
  • 117
2

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();
} 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Just observational, but `client_Price is DBNull` might be a more convenient way of testing that (rather than `DBNull.Value.Equals(client_Price)` - but this answer should work fine – Marc Gravell Nov 14 '13 at 10:54
  • @MarcGravell will `client_price==DBNull.Value` will not work? – शेखर Nov 14 '13 at 11:43
  • @Shekhar that will be a reference equality check, so yes it'll work *except for* in some really evil malicious examples that I could create if you really want, but which shouldn't impact real usage – Marc Gravell Nov 14 '13 at 11:54
  • @MarcGravell I would love to see that example :) – शेखर Nov 14 '13 at 11:55
  • @Shekhar maybe something nasty involving `FormatterServices.GetUninitializedObject`; real edge-case stuff – Marc Gravell Nov 14 '13 at 12:45
0

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.

Karthik Elumalai
  • 1,574
  • 1
  • 11
  • 12