How do I get the inserted id (or object) after an insert with the FormView/ObjectDataSource controls
Posted
by drs9222
on Stack Overflow
See other posts from Stack Overflow
or by drs9222
Published on 2010-02-22T15:38:29Z
Indexed on
2010/04/03
5:53 UTC
Read the original article
Hit count: 352
I have a series of classes that loosely fit the following pattern:
public class CustomerInfo {
public int Id {get; set;}
public string Name {get; set;}
}
public class CustomerTable {
public bool Insert(CustomerInfo info) { /*...*/ }
public bool Update(CustomerInfo info) { /*...*/ }
public CustomerInfo Get(int id) { /*...*/ }
/*...*/
}
After a successful insert the Insert method will set the Id property of the CustomerInfo object that was passed in. I've used these classes in several places and would prefer to altering them. Now I'm experimenting with writing an ASP.NET page for inserting and updating the records. I'm currently using the ObjectDataSource and FormView controls:
<asp:ObjectDataSource
TypeName="CustomerTable"
DataObjectTypeName="CustomerInfo"
InsertMethod="Insert"
UpdateMethod="Update"
SelectMethod="Get"
/>
I can successfully Insert and Update records. I would like to switch the FormView's mode from Insert to Edit after a successful insert. My first attempt was to switch the mode in the ItemInserted event.
This of course did not work. I was using a QueryStringParameter for the id which of course wan't set when inserting.
So, I switched to manually populating the InputParameters during the ObjectDataSource's Selecting event. The problem with this is I need to know the id of the newly inserted record which I can't find a good way to get.
I understand that I can access the Insert method's return value, and out parameters in the ItemInserted event of course my method doesn't return the id using any of these methods. I can't find anyway to access the id or the CustomerInfo object that was inserted after the insert completes.
The best I've been able to do is to save the CustomerInfo object in the ObjectDataSource's Inserting event.
This feels like an odd way to do this. I figure that there must be a better way to do this and I'll kick myself when I see it. Any ideas?
© Stack Overflow or respective owner