The form load event.
Private Sub Start_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Call the method for a new ID
txtID.Text = GenerateID()
End Sub
Method for generating an ID.
Private Function GenerateID() As String
Dim con As New SqlConnection("your connectionstring")
Dim dr As SqlDataReader = Nothing
Dim com As SqlCommand = Nothing
Dim value As String = "0000"
Dim ID As String
Try
' Fetch the latest ID from the database
con.Open
com = New SqlCommand("SELECT TOP 1 <ID> FROM <table> ORDER BY <ID>", con)
dr = com.ExecuteReader(CommandBehavior.CloseConnection)
If dr.HasRows
dr.Read()
value = dr.Item("<ID>")
End If
dr.Close
' Increase the ID by 1
value += 1
' Because incrementing a string with an integer removes 0's
' we need to replace them. If necessary.
If value <= 9 Then 'Value is between 0 and 10
value = "000" & value
ElseIf value <= 99 Then 'Value is between 9 and 100
value = "00" & value
ElseIf value <= 999 Then 'Value is between 999 and 1000
value = "0" & value
End If
Catch ex As Exception
' If an error occurs, check the connection state and close it if necessary.
If con.State = ConnectionState.Open Then
con.Close()
End If
value = "0000"
End Try
Return value
End Function