I'm using an MS Access database (I know...), so to capture the auto-generated primary key, I'm extending the table adapter class. I took me a while to figure this part out, so if that's your problem, future reader, right-click on your dataset file (*.xsd) and select View Code. This will create a partial class. The GetLastID()
method is just a query with SELECT @@IDENTITY
. The trick is that it has to be done when the row is updated, without closing and opening a new connection, so the RowUpdated
event needs to be handled. Here's the code for that:
namespace TimeTrack.TimeTrackDataSetTableAdapters
{
public partial class TimeSlipsTableAdapter
{
public void CustomSetup()
{
Adapter.RowUpdated += Adapter_RowUpdated;
}
private void Adapter_RowUpdated(object sender, OleDbRowUpdatedEventArgs e)
{
if (e.StatementType == StatementType.Insert && e.Errors == null)
{
int lastID = (int)GetLastID();
e.Row["ID"] = lastID;
e.Status = UpdateStatus.SkipCurrentRow;
}
}
}
}
My question is: Is there are way to avoid having to call the CustomSetup()
method?
I would like for somehow to include the event handler assignment in the construction of the table adapter without having to make an additional call. Is there a way?