Adding a row to a DataTable before setting its values

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?
 
B

Bernie Yaeger

Hi Oenone,

No, nothing wrong with the way you're doing it, but you have to find it
again, now that it exists, in order to add the other column information.
Seems like a bit of double work to me. And, you'll now surely have to find
it on its PK, because anything else might return more than one row.

HTH,

Bernie Yaeger
 
O

Oenone

Bernie said:
No, nothing wrong with the way you're doing it, but you have to find
it again, now that it exists, in order to add the other column
information. Seems like a bit of double work to me. And, you'll now
surely have to find it on its PK, because anything else might return
more than one row.

Oh sure -- I'd only do it like this when I'm selecting based on the primary
key. For example:

SELECT * FROM Users WHERE Username = 'MyUser'

(Username being the entire primary key). If this returned a row then I'd
want to update it, if it didn't I'd want to add it. That's the kind of
scenario I'm using this for.

Thanks for your comments,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top