Click here to Skip to main content
15,918,742 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So my problem is when I do the initial add record the program I am making automatically skips the first which is ID 1 and starts adding like so 2, 3, 4, 5, 6.

here is my code:

Dim i As Integer = 0
      I += 1


      Try
          Dim sqlcon As New SqlConnection("mysqlstring")
          Dim sqladapt = New SqlDataAdapter("Select * from [Table]", sqlcon)

          sqlcon.Open()
          Dim cmd As SqlClient.SqlCommand
          Dim sql As String = "insert into [Table] values(@ID,@Question,@Answers,@Howtowork,@Chapter)"
          cmd = New SqlClient.SqlCommand(sql, sqlcon)

          ' Make sure that all tables have the same type of information that can be entered, if not you will recieve an error.
          cmd.Parameters.AddWithValue("@ID", DataGridView1.Rows.Count + I)
          cmd.Parameters.AddWithValue("@Question", TextBox2.Text)
          cmd.Parameters.AddWithValue("@Answers", TextBox3.Text)
          cmd.Parameters.AddWithValue("@Howtowork", TextBox4.Text)
          cmd.Parameters.AddWithValue("@Chapter", TextBox5.Text)

          cmd.ExecuteNonQuery()
          sqlcon.Close()

          MessageBox.Show("New Record Added")

      Catch ex As Exception


      End Try


I figured that it's probably an easy fix that I am not seeing. All I am trying to do is add to the ID unique column using increments of 1. my database must start with 1 and go from there.

What I have tried:

So I tried to put in the first record by just adding it to the table manually before the start of my debugging. This is what happens 1, 3, 4, 5, 6. no matter where I try to start a record it always skips one and after the skip its fine.
Posted
Updated 25-Feb-17 16:55pm
Comments
[no name] 25-Feb-17 20:40pm    
Use an actual identity column in your database and you would not have to deal with this at all. That's what those columns are for.

The problem is that you're letting users type in the ID numbers for records. You NEVER do that.

The ID column should be an auto-numbering or auto-increment column. You let the database generate and assign ID values.

The problem with letting your code do it is that if you have multiple users running the code at the same time, more than one user can query the database to find the maximum ID value that was used. More than one client can get the same value. Then those clients both increment the ID value and try assigning two different record the same ID value. That's really bad.

So, you don't do that. You let the database handle generating ID values, NEVER the client.
 
Share this answer
 
Read Dave's solution and check this out: SQL AUTO INCREMENT a Field[^]
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900