我正在尝试在表单加载时在文本框中生成一个自动增量alphabumeric 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
答案 0 :(得分: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"
答案 1 :(得分: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函数,则MAX函数需要在存储的数字之前包含零,否则字符串ABC2将高于ABC19,因为第4个字符的比较。 当然,当您查询数据表以搜索上述单个结果时,使用ExecuteScalar比使用datareader更简单。