12.17
This conversion from a data-type to xml text, then back to its original data-type, will introduce a pitfall that will plunge many developers into a runtime error. Learning from my past mistakes, I come up with these points that hopefully will save you from experiencing a runtime error (read, an unpleasant call from your customer explaining the problem):
- Always check your data before conversion. VB.Net has these functions to help you: IsDBNull(), IsNothing(), IsNumeric(). Use them wisely.
- Always initialize a variable before assigning a value.
- Try-Catch is there not for nothing.
To illustrate above points, I’ll make a few examples here:
Bad Code:
Dim i as Integer
i = Cint(myDataSet.Tables("MyTable").Row(0).("MyValue"))
ProcessMyVariable(i)
Better Code:
Dim i as Integer = 0
If IsNumeric(myDataSet.Tables("MyTable").Row(0).("MyValue")) Then
i = Cint(myDataSet.Tables("MyTable").Row(0).("MyValue"))
End If
ProcessMyVariable(i)
Best Code:
Dim i as Integer = 0
Try
If myDataset.Tables.Contains("MyTable") Then
If myDataSet.Tables("MyTable").Rows.Count > 0 Then
If IsNumeric(myDataSet.Tables("MyTable").Row(0).("MyValue")) Then
i = Cint(myDataSet.Tables("MyTable").Row(0).("MyValue"))
End If
End If
End If
Catch e as Exception
End Try
ProcessMyVariable(i)
Care to add more?
loading...

No Comment
Add Your Comment