3

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!

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • I noticed you said you use custom logic for data binding, please post it. Also please post the SQL you are using. – pseudocoder Jun 23 '11 at 14:46

2 Answers2

2

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"];

}
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
  • Akram thanks but your code seems not working for me. In fact I need get the PRIMARY KEY and e.Values cannot retrieve it because does not store in as Field. Try to to see with Debug. Let me know your thoughts. thanks – GibboK Jun 23 '11 at 13:54
2

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.

pseudocoder
  • 4,314
  • 2
  • 25
  • 40
  • Hi, thanks for your code. I understand your point and I solve the problem using a very similar approach in my case using EntityDataSource. For my understanding it is not possible get the PK directly to from the DetailsViewInsertedEventArgs because it contaisn Values wich do not include the PK field. Tell me what do you think. Thanks for now! – GibboK Jun 23 '11 at 15:31
  • Sound like you're on the right track now--get the new key at the datasource level. You're welcome! – pseudocoder Jun 23 '11 at 17:27