String variable to text box

gnappi

Newcomer
Joined
Mar 7, 2006
Messages
13
Why do I get a not declared error when I try to send a string to a textbox?

In form load I declare something like:

Dim person1, person2, person3, person4 As String

person1 = "Guy1"
person2 = "Guy2"
person3 = "Guy3"
person4 = "Guy4"

In a checkbox procedure I use:

Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

TextBox2.Text = person1

I block copied in error, above is the correct code snippet
 
Last edited:
There are two problems with your code; first you are dim[ing] assigneeX, and setting personX = "guyX" that will cause an issue right there.

Secondly is variable scope, when you define variables in the scope of a method; they are disposed of by the time the next method executes.

Try defining the variables outside the method (but inside the class) and then access them by the names you defined.

I also recommend for Visual Basic to put these two lines on top of EVERY code file.

Visual Basic:
Option Strict On
Option Explicit On
 
I noticed that you edited your question after Nate had answered, so I thought I would help get Nate's point across:

Try defining the variables outside the method (but inside the class) and then access them by the names you defined.
What he means is that you did something like this:

Code:
Public Class Form
    
    Private Sub Form_Load() Handles Form.Load
        Dim person1, person2, person3, person4 As String '<= NOTE: personX are local to Form_Load
        
        person1 = "Guy1"
        person2 = "Guy2"
        person3 = "Guy3"
        person4 = "Guy4"
    End Sub
    
    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        TextBox2.Text = person1
    End Sub

End Class

What you need to do is:

Code:
[LEFT][COLOR=#b1b100]Public Class Form
    Dim person1, person2, person3, person4 As String '<= NOTE: personX are now local to all of the Form class
    
    Private Sub Form_Load() Handles Form.Load
        person1 = "Guy1"
        person2 = "Guy2"
        person3 = "Guy3"
        person4 = "Guy4"
    End Sub
    
    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        TextBox2.Text = person1
    End Sub

End Class
[/COLOR]
[/LEFT]
 
Back
Top