如何获得自定义自动编号?

时间:2014-12-22 10:06:34

标签: autonumber

我正在尝试从自动编号中获取自定义自动编号。但是,当数据库表中有一些数据运行平稳时,如果数据库表中没有数据,则会给出错误。

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 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

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

试试这个