how do I handle the DBNull fields

1/ I have a checkBox that I want to fill with a value from a Bit field in SQL server. But when the field has a Null value, it gives me an error. How do I convert the DBNull value to a boolean and how do I handle the DBNull values of my table columns.

2/ One more question: I ve seen a technical document about handling Null values from the database in the MSDN articles, but I didn t keep the URL. Does any body know it pls.

Thanks.




Answer this question

how do I handle the DBNull fields

  • Harlow Burgess

    Open the XSD file. For the field giving you the trouble, change the NullValue property to (Null). It's probably currently set to (ThrowException).
  • Avis Phoenix

    You can compare it against DBNull.Value

    Ex:

    foreach (DataRow dtRow in dsTable.Tables[0].Rows )

    Response.Write(dtRow[0]== DBNull.Value "Null Value" : dtRow[0].ToString() );

    Thanks.


  • pppeterd

    u gave me en example while using a sqldatareader. that s perfect.

    How about when I am using a dataset populated by a sqlDataadapter instead.

    Thanks



  • Rufus Leonard

    hi,
    sorry men, i think it is very simple to handle but prob. is not clear so i can not give any truth suggestion.
    bye
    Rajat


  • LouMachado

    Compare the field value with IsDBNull and set the checkbox as true or false as required.

    Ex: Datareader.IsDBNull(0)

    MSDN article for handling Null Values: http://msdn2.microsoft.com/en-us/ms172138.aspx

    Thanks.


  • William Zhi

    These examples are not working for me. I've tried every way I could think (so far) and I always get the same error.

    Here's one of the ways I've tried:

    if(dtMember[0].CCexp.Equals(System.DBNull.Value))

    {

    }

    At runtime I always get this exception:

    catch (System.InvalidCastException e) {

    throw new System.Data.StrongTypingException("The value for column \'CCexp\' in table \'Members\' is DBNull.", e);

    I've tried using "==" instead of equals. I've tried using "Convert.IsDBNull"...

    What am I doing wrong

    EDIT:

    Wow, I just realized that this exception is built into the column!

    public System.DateTime CCexp {

    get {

    try {

    return ((System.DateTime)(this[this.tableMembers.CCexpColumn]));

    }

    catch (System.InvalidCastException e) {

    throw new System.Data.StrongTypingException("The value for column \'CCexp\' in table \'Members\' is DBNull.", e);

    }

    }

    So there's no way for me to even get to the value in this field because as soon as I try to get it, if it's null, I get an exception! I can't even use a try/catch expression. I really hope someone can explain this!


  • Ilia Broudno

    thank you

  • Bill Christian

    >>Wow, I just realized that this exception is built into the column!

    It sure is!! I'm having the same problem. Anyone know of a solution

    Thanks


  • how do I handle the DBNull fields