在动态表单中,如何 link 将文本框 (tbRef) 的内容添加到与其一起生成的按钮中?

In A Dynamic Form, How do I link the contents of a textbox (tbRef) to the button generated along with it?

我仍在学习 VB 并且 运行 遇到了一个没有像样的教程的问题。 我创建了一个动态表单,在每个循环周期中生成一个文本框和一个更新按钮。

我声明了以下全局变量:

Dim tbRef As Textbox
WithEvents btnUpdate As Button

以及稍后在循环中的以下内容

Do Until counter = Maxrows 

counter = counter + 1
...
tbRef = New TextBox
...
Me.Controls.Add(tbRef)


btnUpdate = New button
...
AddHandler btnUpdate.Click, AddressOf btnUpdate_Click
Me.Controls.Add(btnUpdate)
...
tbRef.Text = ds.Tables("Records").Rows(counter - 1).Item(0)

Loop

最后

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
UpdateForm.tbRef.Text = Me.tbRef.Text
UpdateForm.Show()
End Sub

我的问题是:

代码生成正确的布局和正确的控件,如果只返回一个结果,按钮工作正常。如果创建了多个按钮,则所有按钮均引用最后生成的文本框的内容。我在互联网上得到的唯一答案是我必须以某种方式使用 Ctype/DirectCast 将每个文本框的内容投射到用它生成的按钮,但我找不到任何关于如何在这种情况下使用这些运算符的教程。任何帮助将不胜感激。

作为一个选项,您可以使用 Tag property of button and store a reference to the text box in the tag property. Then when you want to find the textbox which the button is responsible for, you can unbox the text box from tag property of the button using DirectCast。按钮本身位于处理事件的方法的 sender 参数中。

您还可以为文本框指定一个名称并将名称存储在标记 属性 中,然后使用该名称查找控件。

例如

For index = 1 To 10
    Dim txt = New TextBox()
    'Set other properties
    'Add it to form

    Dim btn = New Button()
    btn.Tag = txt
    AddHandler btn.Click, New EventHandler(AddressOf btn_Click)
    'Set other properties
    'Add it to form
Next

您可以这样处理事件:

Private Sub btn_Click(sender As Object, e As EventArgs)
    Dim btn = DirectCast(sender, Button)
    Dim txt = DirectCast(btn.Tag, TextBox)
    MessageBox.Show(txt.Text)
End Sub