GibboK
GibboK

Reputation: 73938

DetailsView.ItemInserted Event find the Primary Key (DataKey)

net and C# 4.

I have a DetailsView Control, and I use some custom logic for data binding.

When input data in my DetailsView I would like to use the Event "Inserted" (or another) to get from the DetailsView the Primary Key for the recently inserted data (I suppose using the DataKey properties).

Unfortunately I'm not able to do it.

Do you have any idea how to insert retrive the Primary Key for a item being inserted using the DetailsView?

Thanks for your help!

Upvotes: 3

Views: 3862

Answers (2)

pseudocoder
pseudocoder

Reputation: 4392

First of all, your SQL statement needs to return the SCOPE_IDENTITY().

Second, assuming you are using an ObjectDataSource control, get e.ReturnValue in your datasource control's Inserted event, as in the following example:

protected void dsReferralInsert_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
{
    int intKey;
    if (int.TryParse(e.ReturnValue, out intKey))
    {
        Response.Redirect("ReferralDetail.aspx?ReferralID=" + intKey.ToString());
    }
}

This example uses the new key value to redirect to the detail page.

If you are using a SqlDataSource control, you can programmatically access either Output parameters or ReturnValue parameters, depending on how you wrote the SQL. I'll make an example if you fill me in on what kind of data access you are using.

Upvotes: 2

Akram Shahda
Akram Shahda

Reputation: 14781

DetailsViewInsertedEventArgs.Values gets a dictionary that contains the field name/value pairs for the inserted record.

void CustomerDetailsView_ItemInserted(Object sender, 
    DetailsViewInsertedEventArgs e)
{
    var key = e.Values["Key"];

}

Upvotes: 2

Related Questions