Vb.net 如何生成自定义ID

Vb.net 如何生成自定义ID,vb.net,Vb.net,我想为ID创建一个自定义值。例如,它将以“CR00001”开头,然后当我第二次保存数据时,它将增加数字部分(例如CR00002) 以下是我正在使用的代码: Dim cr_id As String cr_id = "CR00001" Dim iReturn As Boolean Using SQLConnection As New MySqlConnection(strConnectionString) Using sqlCommand As New MySqlCommand(

我想为ID创建一个自定义值。例如,它将以“CR00001”开头,然后当我第二次保存数据时,它将增加数字部分(例如CR00002)

以下是我正在使用的代码:

 Dim cr_id As String
 cr_id = "CR00001"
 Dim iReturn As Boolean

 Using SQLConnection As New MySqlConnection(strConnectionString)
     Using sqlCommand As New MySqlCommand()
         sqlCommand.Connection = SQLConnection
         With sqlCommand
             .CommandText = "INSERT INTO cr_record(idcr_record,Emplid,isu,Nama,date1,DeptDesc,email,change1,reasonchange,problem,priority,reasondescription,systemrequest,attachment) VALUES (@cr_id,@Emplid,@isu,@Nama,@date1,@DeptDesc,@email,@change1,@reasonchange,@problem,@priority,@reasondescription,@systemrequest,@attachment)"
             .CommandType = Data.CommandType.Text
             .CommandTimeout = 5000
             .Parameters.AddWithValue("@cr_id", cr_id)

当您想要生成一个新的ID时,编写一个生成ID的函数,并将此代码复制到那里。将返回类型保留为
String
以返回
newId

    Dim newId As String
    Dim stringId As String
    Dim intId As Integer
    Dim conn As New System.Data.SqlClient.SqlConnection("Your database query string")
    Dim adpt As New System.Data.SqlClient.SqlDataAdapter("Select id from tableName Where date = (SELECT max(date) from tableName)", conn) 'Where tableName is you table
    Dim ds As New DataSet
    adpt.Fill(ds)
    If ds.Tables(0).Rows.Count = 0 Then 'This will check whether any records are there or not
        newId = "CR00001" ' If records are not there then this id will be returned
    Else
        stringId = ds.Tables(0).Rows(0).Item(0).ToString    'This will store your id in string format
        intId = stringId.Substring(2)       ' This will store only integer values from that id
        intId += 1      ' Increment id by 1
        newId = String.Concat("CR", intId)      ' Creating new Id incremented by 1
    End If
    Return newId

每当您要插入时,您应该从数据库表中选择最新的id(您将需要SQL表中的datetime或time列),然后添加VB.Net逻辑以增加它,例如:string SQL=“通过addedon DESC从cr\u记录顺序中选择idcr\u记录”;然后获取其值并使用函数的substring或string.index检查前导零,然后使用switch语句将1添加到id中。如果可能,只需在数据库中保留纯整数作为id号,将一个普通整数转换成一个以
CR
开头的字符串,然后将该整数填充到5位数字,作为一个函数,在向用户显示ID时应用。SALAM@UsmanWaheed i using mysql table。但不要担心。ID字段i使用varchar(10)。自动,不为空。我不明白你说的话。@Damien_不相信我用varchar作为ID列。我该怎么做呢。我只是模糊不清..我在问,为什么不简单地将ID存储在数据库中作为1、2、3等等。当需要向用户显示这些ID时,您可以执行
String.Format(“CR{0:00000}”,ID)
。除非有充分的理由,否则不要将数据作为字符串存储在数据库中,以便应用某种格式。在前端保留格式设置(以及必要时的解析),并以最自然的形式保留数据库中的数据。添加一些示例代码来解释您的解决方案会很有帮助。@sarjit Deliverala感谢您的解释,但我似乎不理解代码。。你能举个例子吗it@RyanKohn我真的很赞成你给我写一些示例代码explaination@RyanKohn我已经试过了..tq的解决方案;)