O
Oenone
Something I've found quite useful to do in my code is to select a record
from my database which may or may not exist, and then if I find that it
doesn't exist to add it to the datatable before I set the field values. For
example:
Dim dt As DataTable
dim dr As DataRow
[...]
'Does the row already exist in the table?
If dt.Rows.Count = 0 Then
'No, so add a new row to the datatable
dr = dt.NewRow
dt.Rows.Add(dr)
'Set the primary key
dr("PKField") = PKValue
Else
'The row exists so get a reference to it
dr = dt.Rows(0)
End If
'Set the other fields
dr("OtherField") = OtherValue
'Update the database
da.Update(dt)
This is convenient because it keeps all the "row doesn't exist" processing
at the start of the code (in the If statement). If I were to add the row to
the datatable after I've set all the field values, I'd need a second If
statement at the end of the code too (just before the call to da.Update)
which checked to ensure the row was actually new, and not an existing row
being updated.
This seems to work fine for me, but every single example I've seen that adds
new rows to a datatable has added it after populating all the values instead
of before. Is there are reason why I should avoid using the above code?
from my database which may or may not exist, and then if I find that it
doesn't exist to add it to the datatable before I set the field values. For
example:
Dim dt As DataTable
dim dr As DataRow
[...]
'Does the row already exist in the table?
If dt.Rows.Count = 0 Then
'No, so add a new row to the datatable
dr = dt.NewRow
dt.Rows.Add(dr)
'Set the primary key
dr("PKField") = PKValue
Else
'The row exists so get a reference to it
dr = dt.Rows(0)
End If
'Set the other fields
dr("OtherField") = OtherValue
'Update the database
da.Update(dt)
This is convenient because it keeps all the "row doesn't exist" processing
at the start of the code (in the If statement). If I were to add the row to
the datatable after I've set all the field values, I'd need a second If
statement at the end of the code too (just before the call to da.Update)
which checked to ensure the row was actually new, and not an existing row
being updated.
This seems to work fine for me, but every single example I've seen that adds
new rows to a datatable has added it after populating all the values instead
of before. Is there are reason why I should avoid using the above code?