Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hw u doing coders .. am facing problem with my code of id number generator
i am building database project and i want to make the id generates it self automaticaly i did it but not how i want it to work ...i want it to Start from 001 and increases every time +1 like this 002,003 untill it reach 100 and so on
how it works now is like this starts from 1 and then 2,3,4,5,6......here is the code.
thank you.
VB
Sub GenerateSerialNo()
        Dim odr As SqlDataReader
        Dim sql As String
        sql = "select max(bookid)as SNo from tbremovedbooks"
        Try
            conn.Open()
            'Application.DoEvents()
            cmd = New SqlCommand(sql, conn)
            odr = cmd.ExecuteReader
            If odr.Read() Then
                iNumOfRecords = DS.Tables("tbremovedbooks").Rows.Count + 1
                'Displaying 1 if there is no data in the table
                If iNumOfRecords = 1 Then
                    txtbookid.Text = "1"
                Else
                    'Ordering the data Serial if more than one record is in the table
                    txtbookid.Text = odr("SNo") + 1
                End If
            End If
            odr.Close()
            cmd.Connection.Close()
            conn.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
Posted
Updated 28-Mar-13 22:39pm
v2
Comments
Hemant Singh Rautela 29-Mar-13 3:30am    
Why not use identity true -(database feature for auto generate id);

&
After below statement
odr = cmd.ExecuteReader;
In your solution you having trouble when no records found---sql = "select max(bookid)as SNo from tbremovedbooks"----
you have to check the variable odr equals DBNull.Value then odr =0

1 solution

Why on hell don't you keep your ID as integer, and just change the format of the number when you are displaying it ?

Basically you have nothing to win to have a varchar primary key.

So, in the database, primary key as int (1, 2, 3, 4, ...).

When you want to display ID :
C#
string formattedId = id.ToString("000");


Simple, and effective.
 
Share this answer
 
v2
Comments
[no name] 1-Apr-13 22:52pm    
thank you for the answer mr.phil.o.

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