2013-02-23 46 views
0

我試圖生成對負載形式的文本框的自動增量alphabumeric ID,並用下面的代碼,我可以插入所述第一組數據,以ID「ABC1」的一個空表,但在下一次加載時,系統會拋出一個錯誤,表示從字符串「ABC1」到double類型的轉換無效。增量在杬VB.NET形式文本框

請問我可以幫忙一下。

謝謝。

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

是格式修復? 3個字母和1個數字? – 2013-02-23 07:49:44

+0

你好,是的,它可以修復格式..謝謝。 – Bladefreak 2013-02-23 08:07:47

+0

如果最後一個值是「ABC9」,該怎麼辦?下一個是ABC10嗎? – 2013-02-23 08:09:59

回答

0

有了這個代碼,你會得到,可以從使用MAX功能,您的數據庫中正確檢索格式化字符串

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 

此代碼將存儲在格式爲「ABC001」,「ABC002」等的ID列字符串中。零的存儲是由MAX功能所需,如果您嘗試使用它的字符串值在號碼前列入否則字符串ABC2將比ABC19更高,因爲第4個字符的比較。 當然,當您查詢數據表以搜索上述單個結果時,使用ExecuteScalar比使用數據讀取器更簡單。

+0

謝謝。這對我有用。 :) – Bladefreak 2013-02-23 08:28:09

0

試試這個

Public Function IncrementString(ByVal Sender As String) As String 
    Dim Index As Integer 
    For Item As Integer = Sender.Length - 1 To 0 Step -1 
     Select Case Sender.Substring(Item, 1) 
      Case "000" To "999" 
      Case Else 
       Index = Item 
       Exit For 
     End Select 
    Next 
    If Index = Sender.Length - 1 Then 
     Return Sender & "1" ' Optionally throw an exception ? 
    Else 
     Dim x As Integer = Index + 1 
     Dim value As Integer = Integer.Parse(Sender.Substring(x)) + 1 
     Return Sender.Substring(0, x) & value.ToString() 
    End If 
End Function 

然後調用它,如下所示:

Dim comm As New SqlCommand 
comm.CommandText = "SELECT MAX(UserID) FROM SQLTable"