我们如何在VB.net中创建控制阵列

我有一个有4个文本框的表格,当任何一个文本框被关注时,它的颜色就会变回黄色,而其他文本框的颜色则变为白色。

当我在vb6中工作时,很容易用控制数组来完成,例如创建文本框控制数组。

设置代码如

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

但在VB.net中,没有控制数组,所以我们做一些事情,如

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

但是它的代码很长,有谁能告诉我一个简单的方法,就像我的vb6代码一样。

解决方案:

将Handles子句链在一起。MSDN的例子。https:/docs.microsoft.comen-usdotnetvisual-basiclanguag-referencestatementshandles-lause#example-2。

在你的情况下,它将看起来像下面。

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

给TA打赏
共{{data.count}}人
人已打赏
未分类

如何使输入代码与打印代码在同一行[重复]。

2022-9-13 14:29:26

未分类

C# LINQ - Prop字符串的值为System.Collections.Generic.List`1[System.String]。

2022-9-13 14:29:28

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索