2016-02-05 61 views
1

代碼是這樣的。而是獲得新的號碼即時得到二月-16-INV-00011和二月-16-INV-000111和二月-16-INV-0001111如何添加日期,年份和字母在vb.net中的自動增量

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 
+0

你應該打開'Option Strict' – Plutonix

+0

也試過這個。但字符$是無效的? –

+2

使用'resultN = retval = String.Format(「{0} -INV- {1}」,DateTime.Now.ToString(「MMM-yy」),newvalue.ToString(「000」))'發佈的答案是使用VS2015功能 – Plutonix

回答

2

你有你需要的一切,它只是你沒有的字符串格式。

Assumuing是NewValue持有您要創建的字符串的下一個數字:

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

注意,如果你正在使用Visual Studio 2013或更低,你將不得不使用的String.Format,而不是$快捷方式:

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 
+0

謝謝先生。但我不明白這一行。 resultN = $「{DateTime.Now.ToString(」MMM-yy「)} - INV- {newValue:000}」 –

+0

我也試過。但字符$是無效的? –

+0

查看我的替代編輯 –