none
System.DBNull problem RRS feed

  • Question

  • I have this code:

    using (SqlDataReader rdr = cmdm.ExecuteReader(CommandBehavior.CloseConnection))
    {
       if (rdr.HasRows == true)
       {
         foreach (System.Data.Common.DbDataRecord row in rdr)
         {
           if (row[7].GetType() != System.DBNull)
           {
              tBoxCheckingBal_pg5.Text = (string)row[7];    // <== runtime error    
           }
           if (row[8].GetType() != System.DBNull)
           {
              tBoxSavingsBal_pg5.Text = (string)row[8];      // runtime error       
           }

    I get a Compile time error: DBNull is a type and it is invalid in the given context.

    If I say null instead of DBNull, then I get a runtime error because those fields are empty, they are nulls.

    What shall I do?


    • Edited by MyCatAlex Saturday, July 21, 2018 9:00 PM
    Saturday, July 21, 2018 8:59 PM

All replies

  • You know what actually worked? Look:

    if (row[7].GetType() == GetType())
    {
       tBoxCheckingBal_pg5.Text = (string)row[7];      
    }
    if (row[8].GetType() == GetType())
    {
       tBoxSavingsBal_pg5.Text = (string)row[8];            
    }
    Very bizarre but who cares?

    • Marked as answer by MyCatAlex Saturday, July 21, 2018 9:12 PM
    • Unmarked as answer by MyCatAlex Sunday, July 22, 2018 6:36 PM
    Saturday, July 21, 2018 9:12 PM
  • if (row[7].GetType() != System.DBNull)

    The proper way to do the type comparison is to use the is operator:

    if (row[7] is System.DBNull)

    Another trick to simplify your code is to use the as operator:

    tBoxCheckingBal_pg5.Text = row[7] as string;

    This will return null if row[7] is not a string, so it will clear the textbox if you read a DBNull.

    If (not here, but maybe in a different type of code) you need to compare the System.Type, then you are missing a call to typeof:

    if (row[7].GetType() != typeof(System.DBNull))

    Monday, July 23, 2018 6:15 AM
    Moderator
  • Try this too:

       if( ! row.IsDBNull(7)) . . .


    Monday, July 23, 2018 7:06 AM