在 VB.NET 表单文本框中增加 AlphaNumeric [英] Increment AlphaNumeric in VB.NET form Textbox

查看:16
本文介绍了在 VB.NET 表单文本框中增加 AlphaNumeric的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to generate an auto increment alphabumeric ID in a textbox on form load, and with the below code, and I can insert the first set of data to ID "ABC1" to an empty table, but on next load, The system will throw an error saying Conversion from string "ABC1" to type double is not not valid.

我可以帮忙看看代码吗?

Can I have some help on the code please.

谢谢.

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

推荐答案

使用此代码,您将获得一个格式化的字符串,可以使用 MAX 函数从您的数据库中正确检索该字符串

With this code you will get a formatted string that could be correctly retrieved from your database using the MAX function

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 比使用数据读取器更简单.

This code will store in the ID column strings formatted as 'ABC001', 'ABC002' and so on. The inclusion of zeros before the number stored is required by the MAX function if you try to use it on string values otherwise a string ABC2 will be higher than ABC19 because the comparison of the 4th character. Of course when you query a datatable to search for a single result like above is simpler to use ExecuteScalar than using a datareader.

这篇关于在 VB.NET 表单文本框中增加 AlphaNumeric的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆