NULL Values from DataTable assigned to Textbox creates error

  • Thread starter Thread starter MU
  • Start date Start date
M

MU

I have a Datatable that I am assigning the values of the row to
textboxes in a form to edit and then save back to the SQL Server.

Though when a value is NULL in the DB, I get this error
Conversion from type 'DBNull' to type 'String' is not valid.

Exception Details: System.InvalidCastException: Conversion from type
'DBNull' to type 'String' is not valid.

Source Error:


Line 1706: Get
Line 1707: Try
Line 1708: Return CType(Me
(Me.tableFamilies.FirstNameColumn),String)
Line 1709: Catch e As
Global.System.InvalidCastException
Line 1710: Throw New
Global.System.Data.StrongTypingException("The value for column
'FirstName' in table 'Families' is DBNull.", e)

Here is where I am assigning the value
txtFirstName.Text = family(0).FirstName

Is there a way to rewrite the above assigning line to test the value
if NULL and just add a blank string?

Thanks
 
Many ways to address this one is

if (!family(0).FirstName == DBNull.Value)
txtFirstName.Text = family(0).FirstName
 
Many ways to address this one is

if (!family(0).FirstName == DBNull.Value)
  txtFirstName.Text = family(0).FirstName

I believe that the problem is not that he is assigning a DBNull value
to the text property of teh TextBox (although that WOULD fail). The
source looks like the generated code from a dataset for a column
property of a datarow where that column has the NullValue property set
to "Throw Exception". In simpler terms, accessing the property is
throwing the exception, not assigning it to the Text property.
Therefore the proper fix for the code would be this: (Note: code is in
VB and is off the top of my head)

If Not family(0).isNull(family.FirstNameColumn) Then
txtFirstName.Text = family(0).FirstName
Else
txtFirstName.Text = "" ' Or other default value
End If

HOWEVER, You could just set the NullValue Property on the FirstName
column to "Empty" so that the generated code for the dataset will
return empty string instead of DBNull.

Hopefully this helps,
Norm
 
Fixed:

Used this
If Convert.IsDBNull(family(0).FirstName) Then
txtFirstName.Text = family(0).FirstName
End If
 
Back
Top