如何在日期,年份和字母表中添加vb.net中的自动增量

时间:2016-02-05 09:08:05

标签: .net vb.net

代码是这样的。但是没有获得新的数字即将获得2月16日INV-00011和2月16-INV-000111和2月16-INV-0001111

Private Function newautonum()

    Dim NewValue As Integer
    'Dim result As String
    Dim resultN As String

    Dim ynow As String = DateTime.Today.ToString("yy")
    Dim Mnow As String = DateTime.Today.ToString("MMM")
    Dim Bilnow As String = Mnow & "-" & ynow & "-"

    Dim qry As String = "select MAX(ID) from tblTrns"

    ConObj = New SqlConnection(ConStr)
    ConObj.Open()

    CmdObj = New SqlCommand(qry, ConObj)
    resultN = CmdObj.ExecuteScalar().ToString()

    If String.IsNullOrEmpty(resultN) Then
        resultN = Bilnow & "INV-000"
        ' resultN = result
    End If

    resultN = resultN.Substring(0)
    Int32.TryParse(resultN, NewValue)
    NewValue = NewValue + 1
    resultN = resultN + NewValue.ToString
    Return resultN

    ConObj.Close()
End Function

现在我尝试了这个但没有运气....从类型'DBNull'转换为'String'类型无效。 getnextvalue错误的功能。

Private Function newautonum() As String

    Dim NewValue As Integer
    Dim result As String
    Dim qry As String = "Select MAX(ID) from tblTrns"

    ConObj = New SqlConnection(ConStr)
    ConObj.Open()

    CmdObj = New SqlCommand(qry, ConObj)
    result = CmdObj.ExecuteScalar().ToString()

    If String.IsNullOrEmpty(result) Then
        result = String.Format("{0}-INV-{1:000}", DateTime.Now.ToString("MMM-yy"), NewValue)
    End If

    Int32.TryParse(result, NewValue)
    NewValue = GetNextValue()
    result = result & GetNextValue.ToString
    Return result

    ConObj.Close()
End Function

1 个答案:

答案 0 :(得分:2)

你拥有所需的一切,它只是你没有的字符串格式。

假设NewValue包含您要为其创建字符串的下一个数字:

 Dim newValue = GetNextValue()
 resultN = $"{DateTime.Now.ToString("MMM-yy")}-INV-{newValue:000}"

注意如果您使用的是Visual Studio 2013或更低版本,则必须使用String.Format而不是$ shortcut:

resultN = String.Format("{0}-INV-{1:000}", DateTime.Now.ToString("MMM-yy"), newValue)

我建议你有一个单独的函数来返回下一个值:

Private Function GetNextValue() As Integer
    Dim qry As String = "select MAX(ID) from tblTrns"

    ConObj = New SqlConnection(ConStr)
    ConObj.Open()

    CmdObj = New SqlCommand(qry, ConObj)
    Dim result = CmdObj.ExecuteScalar()

    If String.IsNullOrEmpty(result) Then
        Return 1
    Else
        Return CInt(result) + 1
    End If
End Function