使用Name属性调用控件并向其中添加事件

时间:2019-03-21 09:26:55

标签: vb.net

我有几个以编程方式创建的texbox。我需要每个文本框都具有一个事件,这意味着1个文本框具有1个与其他事件不同的事件。我使用Name属性为每个文本框命名,希望可以分别标识每个文本框。

for i = 0 to 5
   Dim TextBoxes As New TextBox
   With TextBoxes
     .Name = "InputTextBox" & i
     .AutoSize = True
     .Parent = FlowLayoutPanel1
   End With
Next

如何使用在For循环中设置的Name属性,以便可以将TextChanged事件PER文本框放入。我打算如何处理?正确的方法是什么?

感谢<3

2 个答案:

答案 0 :(得分:0)

我可以建议一种更简单的方法。如果使用单个事件处理程序,则文本框的构建部分会容易得多。然后,在常见的TextChanged事件中,检查传递给处理程序的发件人对象,并使用它为该文本框调用特定的处理程序

所以我们可以

for i = 0 to 5
   Dim TextBoxes As New TextBox
   With TextBoxes
     .Name = "InputTextBox" & i
     .AutoSize = True
     .Parent = FlowLayoutPanel1

   End With

   ' Add the common handler for all textboxes
   AddHandler TextBoxes.TextChanged, AddressOf onChanged
Next

在常见的 onChanged 事件中,您编写此代码

Sub onChanged(sender As Object, e As EventArgs)
    Dim t As TextBox = CType(sender,TextBox)
    Select Case t.Name
        case "inputTextBox0"
           HandleInputTextBox0()
        case "inputTextBox1"
           HandleInputTextBox1()
        ..... and so on....
    End Select
End Sub

但是,如果您准备了一个Dictionary(字典),其中每个键是文本框的名称,每个值是要对该框执行的操作,那么我们也可以摆脱这种选择案例的情况。

Dim dict As Dictionary(Of String, Action) = New Dictionary(Of String, Action) From
{
    {"inputTextBox0", AddressOf HandleInputTextBox0},
    {"inputTextBox1", AddressOf HandleInputTextBox1}
}

并将常用的textchanged处理程序更改为简单的两行代码

Sub onChanged(sender As Object, e As EventArgs)
    Dim t As TextBox = CType(sender,TextBox)
    dict(t.Name).Invoke()
End Sub

答案 1 :(得分:0)

感谢@Steve。这就是我解决问题的方式

for i = 0 to 5
  Dim TextBoxes As New TextBox
  With TextBoxes
    .Name = "InputTextBox" & i
    .AutoSize = True
    .Parent = FlowLayoutPanel1
    AddHandler .TextChanged, AddressOf InputPercentage
  End With
Next

Friend Sub InputPercentage(sender as Object, e as EventArgs)
  Dim txt As TextBox = CType(sender, TextBox)
  MessageBox.Show(txt.Name)
End Sub

我能够获得控件的名称。谢谢!