Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 404
  • Last Modified:

Primary key insert in a Detailsview control.

I'm using a Detailsveiew control for adding a new contact to tbl_contacts. The control is bound to a class in the middle tier...clscontacts.
I need to take a new primary key from a table of lastkeysused and use it for the new contact being entered in the Detailsview. I can retrieve the new key...but I cannot get it into the detailsview row so it can be included in the INSERT.
Can it be done? or am I taking the wrong approach?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'Get the next key for this insert
            Dim mylist As List(Of clslastkey)
            Dim myclslastkey As clslastkey
            mylist = LastKeyDAL.GetLastKey() 'get the list...just 1 record in this case
            myclslastkey = mylist(0) ' get the first item in the list
            lblnextcontactID.Text = myclslastkey.nextcontactID 'get the next key        
        End If
    End Sub

Open in new window

2 Solutions
Chris, normally the database would be setup to generate the new number itself (autonumber type) in Access, or identity property set to true in SQL Server.

Trying to guess what the next value in the database would be would be problematic if
a) the last record entered has been deleted
b) two users are concurrently in the process of creating a user.

Maybe a better approach is to generate the record, and then query the database to find out what the value of what last record inserted is.

chrisgreavesAuthor Commented:
Hi Mildurait,
Thanks for the comments, you make good points regarding the deletion of records and the simultaneous insertion of new records by multiple users...I need to have that discussion with my instructor at the next class.
BUT, for now, I am "instructor bound" to do it this way.
I woke up fresh this morning and figured out these 2 lines, which take care of my immediate needs:
            Dim row1 As DetailsViewRow = DetailsView1.Rows(0)
            row1.Cells(1).Text = myclslastkey.nextcontactID

Thanks again, and hopefully, you are nowhere near the bushfires.

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now