Vb.net – How to make a variable that is recognised through multiple forms

vb.net

I have a problem with my program. I wanted to know how i can make a global variable like an integer be recognised in any form so in essence linking to two forms together.

Also how do I store an integer that has been typed by the user into the textbox? This integer will then be stored in the global variable. I have got two forms, one is for the user to interact with and the other is going to be used for displaying the global variable.

Best Solution

To make a global variable (in your case, an integer), you should declare:

Public x As Integer

Outside of any methods or subroutines.

Having the user click on a command button is a good way to store a variable (or any other information) after it has been typed into a textbox. The command button's code would go something like this:

Private Sub commandButton_Click()
    x = textBox.Text
End Sub

And if you want to guard against non-numeric inputs in the textbox, you might consider adding a simple If statement:

If IsNumeric(textBox.text) Then
    x = textBox.Text
Else
    MsgBox "Please enter a numeric value"
End If

You can also write some simple lines of code that, if the input is not text (these would go in the Else condition of the If statement), will automatically redirect the user's focus back to the textbox and highlight the offending input:

textBox.SetFocus
textBox.SelStart = 0
textBox.SelLength = Len(textBox.Text)

SetFocus puts the user's cursor back on the textbox, SelStart places the cursor position at the beginning of the input text, and SelLength sets the highlighted length to the entirety of the text.

(Note: this is all VB6 code, but it should be very similar if you're working with a different version.) Hope this helps!

Related Question