0

我正在尝试在表单加载时在文本框中生成一个自动递增的字母数字 ID,并使用下面的代码,我可以将 ID 为“ABC1”的第一组数据插入到空表中,但在下一次加载时,系统将抛出一个错误,说从字符串“ABC1”转换为双精度类型无效。

我可以对代码有一些帮助吗?

谢谢。

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
4

2 回答 2

0

试试这个

    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"
于 2013-02-23T07:59:36.487 回答
0

使用此代码,您将获得可以使用 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 函数需要在存储的数字之前包含零,否则字符串 ABC2 将高于 ABC19,因为比较第 4 个字符。当然,当您查询数据表以搜索像上面这样的单个结果时,使用 ExecuteScalar 比使用数据读取器更简单。

于 2013-02-23T08:15:19.097 回答