0

I have here a weird problem, this code works but it stops incrementing when it reaches the value of 10 it should be able to +1 and make it 11 but it stops. I don't know what is causing this, really confused right now.

Here is my code:

Dim i As Integer
i = Integer.Parse(TextBox1.Text) + 1
TextBox1.Text = i.toString()

Could there be something that caused this? Any help or advice will be gladly accepted. Thanks in advance

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
Marc Intes
  • 737
  • 9
  • 25
  • 51

2 Answers2

2

If that code is a revision from your other recent question , the relevant code is this:

Private Sub LoadValue( )
    Dim i As Integer    
    Dim cmd As OleDbCommand = New OleDbCommand

    With cmd
        .CommandText = "SELECT MAX(Guard_ID) FROM Guard"
        .CommandType = CommandType.Text
        .Connection = Conn
        .ExecuteNonQuery()

        Dim reader As OleDbDataReader = cmd.ExecuteReader

        If reader.Read Then

           ' posted code seems to be a 
           ' revision of this:
           TextBox1.Text = reader.GetString(0)
           i = TextBox1.Text + 1
           TextBox1.Text = i

            reader.Close()
        End If
    End With
 End With

The problem is not with the incrementing, but running a MAX query on a TEXT column. Consider a table with IDs of {"0", "1", "2", "10", "11"}. What is the MAX value of that series? Since the column is TEXT, a Text Comparison is done, and the answer is not "11" but "2", because the character 2 has a higher value than the character 1 which is the first digit in both "11" and "10" ("10" <> 10 <> "ten").

Once there are 10 records, your MAX query will only ever return "9" because that is the largest value for the first character of any string of numerals.

In code and in databases, things that you want to treat as numbers have to be a numeric type. This is even more true of Date types, converting them to strings doesnt help. The solution is to change the database column type from Text to Integer, perhaps an AutoNumber and let the DB do all that work for you.

Community
  • 1
  • 1
Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
1

I tried this

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer
    Dim itb As Integer
    'make sure the number in the tb is valid
    If Integer.TryParse(TextBox1.Text, itb) Then
        i = itb + 1
        TextBox1.Text = i.ToString()
    Else
        'not a number
        Stop
    End If
End Sub

and it worked just as expected.

dbasnett
  • 11,334
  • 2
  • 25
  • 33