Friday, March 10, 2006

VS2005: Formview - Get Row ID of inserted record

In VS 2005 define a SQLDatasource or ObjectDatasource with an insert statement and add an output parameter. Then use the following SQL statement to fill your output parameter (use ; to separate the statements):

INSERT INTO Values ();

select @NewID = SCOPE_IDENTITY() ;

On your form catch the inserted event of the used datasource and save the generated ID (for example in the viewstate):

protected void datasource_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
{
ViewState["ID"] = e.OutputParameters["NewID"];
}


In the Save function you can retrieve the new ID by getting it from the querystring (if that is the case) or by using the viewstate (which you filled above):

private int Save()
{
//edit or update
if (fvApplicatie.CurrentMode == FormViewMode.Insert)
{
fvApplicatie.InsertItem(false);
//Retrieve ID from Viewstate
return int.Parse(ViewState["ID"].ToString());
}
else
{
//Retrieve ID from Querystring
fvApplicatie.UpdateItem(false);
return int.Parse(Request["ID"].ToString());
}
}

No comments: