gnappi Posted February 6, 2009 Posted February 6, 2009 (edited) 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 Edited February 6, 2009 by gnappi Quote
Nate Bross Posted February 6, 2009 Posted February 6, 2009 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. Option Strict On Option Explicit On Quote ~Nate� ___________________________________________ Please use the [vb]/[cs] tags on posted code. Please post solutions you find somewhere else. Follow me on Twitter here.
tfowler Posted February 6, 2009 Posted February 6, 2009 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: 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: [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] Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.