将变量传递给动态创建的按钮单击事件处理程

时间:2017-11-13 19:19:34

标签: vb.net winforms

我在FlowLayoutPanel中动态创建一个文本框和按钮:

        Dim txtRating As New TextBox
        txtRating.Name = "buildingRating_" + intCount.ToString

        Dim btnAddRating As New Button
        btnAddRating.Name = "addRating_" + intCount.ToString

然后我为按钮创建一个事件处理程序:

    AddHandler btnAddRating.Click, AddressOf HandleAddRatingButtonClick

每个文本框和按钮将使用intCount值相互关联,因此它看起来像这样:

buildingRating_1   addRating_1
buildingRating_2   addRating_2
buildingRating_3   addRating_3
etc....

我需要获取与按钮关联的文本框的值。

例如,如果用户单击名为addRating_1的按钮,则buildingRating_1的文本值将保存为数据库...

有没有办法获得该关联或将intCount传递给我正在创建的btnAddRating.Click事件?

谢谢!

1 个答案:

答案 0 :(得分:2)

从按钮名称中提取索引,并使用它重新创建文本框的名称。然后在表单上找到文本框。

21000

如果文本框位于容器(面板,分组框等)中,则代替foreach ($arr as $keys) { foreach($keys as $value) { echo "{$value} "; } echo "\n"; } 执行Private Sub HandleAddRatingButtonClick(sender As Object, e As EventArgs) Dim button = DirectCast(sender, Button) Dim index = button.Name.Split("_"c).Last() Dim textboxname = "buildingRating_" & index Dim textbox = Me.Controls.OfType(Of TextBox).Single(Function(tb) tb.Name = textboxname) Dim text = textbox.Text ' this is the text End Sub