Reputation: 57
I have a form with 4 text box when any textbox get focus then its change back color yellow and other text box back color change to white.
When i work in vb6 its easily done with control array For example Create text box control array
set The code like
Private Sub text1_GotFocus(Index As Integer)
Call color
Text1(Index).BackColor = vbyellow
End Sub
Private Sub color()
For I = 1 To 4
Text1(I).BackColor = vbWhite
Next I
But in VB.net There is no control array so we do some thing like
Module Module1
Public mytext() As TextBox = {Form1.TextBox1, Form1.TextBox2, Form1.TextBox3, Form1.TextBox4}
End Module
Sub color()
For i = 0 To 3
mytext(i).BackColor = Drawing.Color.White
Next i
End Sub
Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles
TextBox1.GotFocus
color()
ChangeColor(sender)
End Sub
Private Sub TextBox2_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.GotFocus
color()
ChangeColor(sender)
End Sub
Private Sub TextBox3_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox3.GotFocus
color()
ChangeColor(sender)
End Sub
Private Sub TextBox4_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox4.GotFocus
color()
ChangeColor(sender)
End Sub
Sub ChangeColor(ByRef box As TextBox)
box.BackColor= Drawing.Color.Yellow
End Sub
End Class
But its long code can any one tell me a simple way like my vb6 code
Upvotes: 0
Views: 253
Reputation: 3207
Another option:
You could centralize all your textboxes GotFocus
events on the same method:
' In the New() Sub of your Form:
For Each t As TextBox In {TextBox1, TextBox2, TextBox3, TextBox4}
AddHandler t.GotFocus, AddressOf TextBoxList_GotFocus
Next
The TextBoxList_GotFocus
signature:
Private Sub TextBoxList_GotFocus(sender As Object, e As EventArgs)
color()
ChangeColor(sender)
End Sub
Close enough to your previous handling?
Upvotes: 1
Reputation: 6131
Chain the Handles clauses together. MSDN example: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/handles-clause#example-2
In your case it would look like the following:
Private Sub TextBoxChangeColor_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus, TextBox4.GotFocus
Dim this As TextBox = DirectCast(sender, TextBox)
this.BackColor = Color.Yellow
End Sub
Private Sub TextBoxChangeColor_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus, TextBox4.LostFocus
Dim this As TextBox = DirectCast(sender, TextBox)
this.BackColor = Color.White
End Sub
Upvotes: 3