簡體   English   中英

VB.NET表單文本框中的AlphaNumeric增量

[英]Increment AlphaNumeric in VB.NET form Textbox

我正在嘗試在窗體加載時使用以下代碼在文本框中生成自動增量字母數字ID,並且可以使用以下代碼將第一組ID為“ ABC1”的數據插入到一個空表中,但是在下一次加載時,系統將引發錯誤,指出從字符串“ ABC1”到類型double的轉換無效。

請給我一些代碼方面的幫助。

謝謝。

Try

    Dim con As New SqlClient.SqlConnection()
        con.Open()
        Dim myCommand As SqlCommand
        Dim pdid As String
        myCommand = New SqlCommand("select ISNULL(Max(ID),0) From SQLTable", con)
        Dim reader As SqlDataReader = myCommand.ExecuteReader
        reader.Read()
        id= reader.Item(0) + 1
        pdidbox.Text = "ABC" + pdid.ToString()
        reader.Close()
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    End Try

嘗試這個

    Public Function IncrementString(ByVal Sender As String) As String
    Dim Index As Integer
    For Item As Integer = Sender.Length - 1 To 0 Step -1
        Select Case Sender.Substring(Item, 1)
            Case "000" To "999"
            Case Else
                Index = Item
                Exit For
        End Select
    Next
    If Index = Sender.Length - 1 Then
        Return Sender & "1" '  Optionally throw an exception ?
    Else
        Dim x As Integer = Index + 1
        Dim value As Integer = Integer.Parse(Sender.Substring(x)) + 1
        Return Sender.Substring(0, x) & value.ToString()
    End If
End Function

然后如圖所示調用它:

Dim comm As New SqlCommand
 comm.CommandText = "SELECT MAX(UserID) FROM SQLTable"

通過此代碼,您將獲得可以使用MAX函數從數據庫正確檢索的格式化字符串。

Dim curValue as Integer
Dim result as String
using con as SqlConnection = new SqlConnection("server=localhost;initial catalog=TEMPDB;Trusted_Connection=True;")
    con.Open()
    Dim cmd  = new SqlCommand("Select MAX(ID) FROM TEST", con)
    result = cmd.ExecuteScalar().ToString()
    if string.IsNullOrEmpty(result) Then
        result = "ABC000"
    End If

    result = result.Substring(3)
    Int32.TryParse(result, curValue)
    curValue = curValue  + 1
    result = "ABC" + curValue.ToString("D3")

End Using

此代碼將在ID列中存儲格式為'ABC001','ABC002'等的字符串。 如果您嘗試在字符串值上使用MAX函數,則MAX函數要求在存儲的數字之前包含零,否則,由於比較第4個字符,字符串ABC2將高於ABC19。 當然,當您查詢數據表以搜索上述單個結果時,使用ExecuteScalar比使用數據讀取器更簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM