How to get custom autonumber?

123 views Asked by At

I am trying to get custom autonumber from a autonumber. But, when there is some data in the database table it runs smooth and when there is no data in database table it gives me error.

Private Sub CustomNo()
    Dim comm As OleDbCommand
    Dim commStr As String = "SELECT MAX(ID) FROM Table"
    Dim RD As OleDbDataReader
    Dim i As Integer

    conn = New OleDbConnection(connStr)
    conn.Open()

    comm = New OleDbCommand(commStr, conn)
    RD = comm.ExecuteReader

    While RD.Read
        If Not IsDBNull(RD.GetInt32(0)) = False Then
            i = RD.GetInt32(0)
            CustN = "ABC-" & i + 1
            Custom_NoTextBox.Text = CustN
            Exit While
        Else

            i = 0
            CustN = "ABC-" & i + 1
            Custom_NoTextBox.Text = CustN

        End If
    End While

    conn.Close()
End Sub
2

There are 2 answers

0
Tarak Bhavsar On
Private Sub CustomNo()

    Dim CountCom As OleDbCommand
    Dim CountComStr As String = "SELECT COUNT(*) FROM Table"
    Dim j As Integer
    Dim i As Integer

    conn = New OleDbConnection(connStr)
    conn.Open()

    CountCom = New OleDbCommand(CountComStr, conn)
    j = CountCom.ExecuteScalar()

    If j = 0 Then
        i = 1
    Else
        Dim comm As OleDbCommand
        Dim commStr As String = "SELECT MAX (ID) FROM Table"
        Dim RD As OleDbDataReader

        comm = New OleDbCommand(commStr, conn)
        RD = comm.ExecuteReader
        While RD.Read
            i = RD.GetInt32(0)
        End While
        i = i + 1
    End If

    Custom_NoTextBox.Text = "ABC-" & i

    conn.Close()
End Sub
0
Galahad On
Friend Function cmd_excuteScalar()    
    conncet()
    cmd = New SqlCommand(sql, cn)       
    Return cmd.ExecuteScala        
End Function

Private Sub get_autonumber_normal()  
    sql = "select max(product_id) from product_tb " 
    Try
        txt_productcode.Text = cmd_excuteScalar() + 1 excuteScalar 
    Catch ex As Exception                                 
        txt_productcode.Text = "1"
    End Try
End Sub

Private Sub frm_Number_Load(sender As System.Object, e As EventArgs)
    Handles MyBase.Load
    get_autonumber_normal()
    refresh_data_table()
End Sub

try this