For an object such as a DataGridView item or a data set item is the .tostring method safe to use against possible DBnull's?
The application is a mysqlconnector fed DB application which pretty much uses standard query's, but I do come across DBNull quite a bit. Keeping coding efficiency in mind, is the following safe?
Module DataCheck
Public Function SafeDataSTR(DBItem As Object) As String
If Not (IsDBNull(DBItem)) Or Not (IsNothing(DBItem)) Then
Return DBItem.ToString
Else
Return ""
End If
End Function
End Module
'Elsewhere in the galaxy....'
With tempDS.Rows.Item(0) 'tempDS is a standard dataset'
Textbox1.Text = SafeDataSTR(.Item("SupplierDetails")) 'Not necessarily a text box, just an example'
The original solution was:
If Not IsDBNull(.Item("JobDescription")) Then _
jobinfo.Job_Description = .Item("JobDescription")
Which has worked in the past but is there a better safer way to protect yourself from these?
EDIT: Sorry, would DataRow.item("Column").tostring be just as safe?
EDIT: Final Version:
Public Function SafeData_Rowfeed(row As DataRow, ItemName As String) As String
Try
If Not (IsDBNull(row.Item(ItemName))) Then
Return row.Item(ItemName).ToString
ElseIf IsNothing(ItemName) Then
Throw New IndexOutOfRangeException("Supplied Column " & ItemName & "Not found or is Nothing")
Else
Return ""
End If
Catch ex As System.ArgumentException
Console.WriteLine(ex.Message)
Return "Column Does Not Exist"
End Try
End Function