简体   繁体   中英

How to reset Identity Column Of Table when a record is deleted?

I have a Datagridview which gets populated with some data from SQL Server. This works fine no problem at all.

Each time I insert or update records in the table, I want to RESEED an IDENTITY column named CarID of a table, but the sequence of IDS appears not good because sometimes records are deleted.

In my code, I use 'SQLCOMMANDBUILDER' to perform an insert ,update or delete operations.

I have tried the following code below but i throws an exception error which says "Cannot find table 0."

Where should I fix ??

//THESE ARE CODE TO RESEED AN IDENTITY COLUMN

Sub ResetIDColumn()
    Try
        Dim querystring As String = "declare @max int " &
                        "Select @max=max([CarID]) FROM [dbo].[Cars]" &
                        "if @max IS NULL SET @max = 0 " &
                        "DBCC CHECKIDENT ('[Cars]', RESEED,@max)"
        ds = New DataSet
        da = New SqlDataAdapter(querystring, con)
        cmdbuilder = New SqlCommandBuilder(da)
        da.Fill(ds)
        DgvCarList.DataSource = ds.Tables(0)

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

 //CODE TO PUPOLATE DATAGRIDVIEW
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) 
Handles MyBase.Load
    Try
        Dim querystring As String = "SELECT * FROM [dbo].[Cars]"
        ds = New DataSet
        da = New SqlDataAdapter(querystring, con)
        cmdbuilder = New SqlCommandBuilder(da)
        da.Fill(ds)
        DgvCarList.DataSource = ds.Tables(0)

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

//CODE TO INSERT OR UPDATE DATA

Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdate.Click
    ResetIDColumn()
    Try
        da.Update(ds.Tables(0))
        MessageBox.Show("Update was successful!", "Data")
        Loaddata()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

//CODE TO LOAD DATA 
Sub Loaddata()
    Dim querystring As String = "SELECT * FROM [dbo].[Cars]"
    ds = New DataSet
    da = New SqlDataAdapter(querystring, con)
    cmdbuilder = New SqlCommandBuilder(da)
    da.Fill(ds)
    DgvCarList.DataSource = ds.Tables(0)
    DgvCarList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
End Sub

I tried harder and harder and finally I discovered that-;

  1. You need to create a new dataset,Sqlcommandbuilder and new dataadapter then query
    data from your table (using select statement) at the same time execute command to reset id using 'single querystring'.

  2. The aim of executing two command is such that all the results are stored in SINGLE DATASET

  3. I decided to Call this sub after a record is deleted from table.

CODE:

// Button click to delete a record
 Try
        If ds.Tables(0).Rows.Count > 0 Then
            Dim rowposition As Integer = DgvCarList.CurrentRow.Index
            Dim rowdelete As DataRow = ds.Tables(0).Rows(rowposition)
            rowdelete.Delete()
            da.Update(ds)
            MessageBox.Show("Delete was success!", "Data")
            Loaddata()
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

  // After delete completed Go and reset an identity column 
    ResetIDColumn()


  // code to reset an identity column
 Sub ResetIDColumn()
    Try
        Dim querystring As String = "SELECT * FROM [dbo].[Cars] go " &
                                     "DECLARE @max INT " &
                        "Select @max=max([CarID]) FROM [dbo].[Cars]" &
                        "if @max IS NULL SET @max = 0 " &
                        "DBCC CHECKIDENT ('[Cars]', RESEED,@max)"
        ds = New DataSet
        da = New SqlDataAdapter(querystring, con)
        cmdbuilder = New SqlCommandBuilder(da)
        da.Fill(ds)
        DgvCarList.DataSource = ds.Tables(0)

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub


          ...................Thank you all..................................

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM