How do I get the inserted id (or object) after an insert with the FormView/ObjectDataSource controls?
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?
If you need to retrieve the return value of the invoked insert method on a objectdatasource, use the “Inserted” event like so:
protected void ObjDS_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
{
int retvalue = Convert.ToInt32(e.ReturnValue);
}
No parameter needed to catch the return value. For the Update method use the “Updated”
精彩评论