Search code examples
vb.netincrementnvarchar

Auto Increment nvarchar value in vb.net


I'm having a UserID field in my table and I need to get that value in my app and whenever I would like to add a new record it should increment by value '1'.

So this is how I'm trying to get the last ID enetered from my table.

For Example I'm having a value as "A000" and I need to increment that value by '1' so that it should become "A001" and so on..and after 'A999' as pointed out by PinnyM' it should become 'A1000'.

I don't want to write any stored procedures or anyother way from database.I would like to do it in a simpler way using my existing code.

 Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=True"
 Dim con As New SqlConnection(strConnection)
 con.Open()
 Dim comm As New SqlCommand
 comm.CommandText = "SELECT MAX(UserID) FROM Customers"
 comm.Connection = con
 Dim MaxUserID As Object = comm.ExecuteScalar()
 txtID.text=MaxUserID

Solution

  • I got it managed to work by doing it this way:

    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