首页 > 解决方案 > 生成字母数字 ID VB.NET 时出错

问题描述

我试图通过连接用户公司 + 自动生成的 ID 来生成唯一 ID

我的字母数字输出是“SNC001”,但是当我尝试生成下一个 ID 时,出现以下错误:

从字符串“SNC001”到类型“Integer”的转换无效。

PS:“SNC”来自这个 frm_Main_Menu.lblCompany.Text

Dim maxid As Object
Dim strid As String
Dim intid As Integer
Dim cmdid As New MySqlCommand

cmdid.Connection = cnn_MYSQL
cmdid.CommandText = "SELECT MAX(printed_id) as maxid FROM imports"
maxid = cmdid.ExecuteScalar

If maxid Is DBNull.Value Then
    intid = "001"
Else
    strid = CType(maxid, String)
    intid = CType(strid, String)
    intid = intid + 1
End If

Dim autoid As String = frm_Main_Menu.lblCompany.Text & intid.ToString().PadLeft(3, "001")

Dim cmd66 As New MySqlCommand
cmd66.Connection = cnn_MYSQL
cmd66.CommandText = "UPDATE imports " & _
    " SET printed='" & "Y" & "', printed_id='" & autoid & "'" & _
    " WHERE TIN = '" & id_selected &"'"
cmd66.ExecuteNonQuery()

标签: mysqlvb.net

解决方案


您正在将具有String类型的整个 ID 段分配给Integer该行上的字段/变量,这是完全错误的并导致InvalidCastException

intid = CType(strid, String) ' throws conversion error

Substring()正确的方法是使用从数字部分(即索引为 3 的第 4 个元素)开始切掉前缀,然后使用Convert.ToInt32()orInteger.Parse()方法将余数转换为整数:

' using Convert.ToInt32
intid = Convert.ToInt32(strid.Substring(3, 3))

' alternative with Integer.Parse
intid = Integer.Parse(strid.Substring(3, 3))

边注:

最好使用参数化查询而不是字符串连接来构建查询,请参见以下示例:

cmd66.CommandText = "UPDATE imports SET printed = 'Y', printed_id = @autoid WHERE TIN = @id_selected"
cmd66.Parameters.Add("@autoid", MySqlDbType.VarChar).Value = autoid
cmd66.Parameters.Add("@id_selected", MySqlDbType.Int).Value = id_selected
cmd66.ExecuteNonQuery()

推荐阅读