Tuesday, October 19, 2010

VB.NET, DB Nulls, and strings

If you are dealing with a database that isn't enforcing "no nulls" then you may frequently get nulls back when you are expecting a string. Although you could do this:

if dr.Item("middle_name") is DBNull.Value then
txtMiddleName.Text = ""

It is easier to just write:

txtMiddleName.Text = dr.Item("middle_name").ToString

because adding "ToString" will convert nulls to "" empty strings.
If you omit the "ToString", any nulls will generate an error (converting a Null to a String).

No comments: