Today, I’m going to teach you how to create an autonumber in the TextBox. It auto generates the number in the TextBox every time you click the Button. This is very important, why? Because this number serves as your primary key. For instance, when saving the data or record in the database you have to put a specific I’d number so that, the data or records will not be redundant when retrieving it from the database.
Open the visual basic. After that, add a button and a textbox in the form.
After arranging the Button and TextBox, double click the button to fire the click event handler. Then, put the code into it.
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- 'DECLARE A VARIABLE FOR STORING NUMBER
- Dim inc As Integer
- 'STORE A NUMBER WHICH IS 1 TO A VARIABLE THAT YOU HAVE DECLARED
- inc = 1
- 'THIS FORMULA WORKS FOR INCREMENTING A VALUE THAT'S IN THE TEXTBOX.
- inc = inc + Val(TextBox1.Text)
- 'PUTING THE VALUE OF A VARIABLE IN THE TEXTBOX
- TextBox1.Text = inc
- End Sub
Every time you click the button, the number in the TextBox will be incremented by 1.
Press F5 on the keyboard to run your project.