I am trying to initialize an object with data from database return in a dataset as below:
Class Pdf
Public FileId As Integer
Public AccountNumber As Integer
Public DateSaved As DateTime
Public FileName As String
Public DateImported As DateTime
Scenerio 1 I can intialize the object like this:
Dim pdf = New Pdf With {.FileId = ds.Tables(0).Rows(i)("fileid"),
.AccountNumber = ds.Tables(0).Rows(i)("accountnumber"),
.DateSaved = ds.Tables(0).Rows(i)("datesaved"),
.FileName = ds.Tables(0).Rows(i)("filename"),
.DateImported = ds.Tables(0).Rows(i)("dateimported")
}
But this is not working, because column data can be null and I am not if how to do a db null check in this approach.
Then I have scenerio 2:
Dim pdf As New pdf
If Not IsDBNull(ds.Tables(0).Rows(i)("fileid")) Then
PdfFileId = ds.Tables(0).Rows(i)("fileid")
Else
PdfFileId = 0
End If
If Not IsDBNull(ds.Tables(0).Rows(i)("accountnumber")) Then
pdf.AccountNumber = ds.Tables(0).Rows(i)("accountnumber")
Else
pdf.AccountNumber = 0
End If
If Not IsDBNull(ds.Tables(0).Rows(i)("datesaved")) Then
pdf.DateSaved = Format(ds.Tables(0).Rows(i)("datesaved"), "yyyy-MM-dd")
Else
pdf.DateSaved = Nothing
End If
If Not IsDBNull(ds.Tables(0).Rows(i)("dateimported")) Then
pdf.DateImported= Format(ds.Tables(0).Rows(i)("dateimported"), "yyyy-MM-dd")
Else
pdf.DateImported= Nothing
End If
How can I do this to avoid doing so many If
statements below. This way seems inefficient to me, can anyone suggest an better approach to initializing the object in scenario one or two? If the question is unclear, please do let me know, I will try and explain.
Please note this is sample data.
See Question&Answers more detail:os