DataAdapter.Update() adding row with identity field

P

PeterB

I have a datatable and use a SqlCeDataAdapter to insert/delete data to a
database. I don't call the update method until I leave my form where I can
modify this particular table. When I add a row I don't get the identity
field value updated into the datatable from the DB. I got this code snippet
from ADO docs using RowUpdate event:

private static void sqlAdapt_RowUpdated(object sender,
SqlCeRowUpdatedEventArgs e)
{
int newID = 0;
SqlCeCommand sqlCmd = new SqlCeCommand("SELECT @@IDENTITY", sqlConn);

if (e.StatementType == StatementType.Insert)
{
newID = (int)sqlCmd.ExecuteScalar();
e.Row["myIdentField"] = newID;
}
}

The event is fired when I call Adapter.Update(), which is called when I
leave the form. This means several rows may have been added and the code
above wouldn't work since the @@IDENTITY retrieves the last inserted
identity value. So my question is now how would I go about to retrieve the
identity field values if it isn't just the last inserted identity value? Is
it impossible? Is it good practice to call Adapter.Update() whenever a row
is inserted/deleted etc. instead of, as I do, when all rows has been added
and deleted by the use?

I know I could use another combination of unique fields to retrieve the
identity value, but I am curious if there is any other better ways. Maybe
you don't have another unique index...

thanks,

Peter
 

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