使用存储为字符串的文本框名称访问复选框的值的方法?

Way to access the value of a checkbox with the name of the textbox stored as a string?

我正在为学校开展一个项目,该项目使用咖啡馆的菜单。长话短说,我有一些代码在数据库中运行,并为每个条目向屏幕添加几个新元素,包括两个复选框和一个按钮

创建时按钮的名称是“btn_”,然后是产品ID,两个复选框分别标记为“cb1_”和“cb2_”以及ID。 我想要的预期行为是,当按下按钮时,读取与按钮具有相同 ID 名称的两个复选框值。

我有代码:

创建button/boxes

    Dim button As Button = New Button
    button.Text = "Add to order"
    button.Name = "btn_" & array(0)
    button.Width = 154
    button.Height = 55
    button.Location = New Point(298, (262 * i) + 203)
    button.Font = New Font("Microsoft Sans Serif", 16)
    Me.Controls.Add(button)
    AddHandler button.Click, AddressOf addToOrderButtonClicked

    'check box 1
    Dim checkBox2 As CheckBox = New CheckBox
    checkBox2.AutoSize = True
    checkBox2.Name = "cb1_" & array(0)
    checkBox2.Location = New Point(12, (262 * i) + 229)
    checkBox2.Font = New Font("Microsoft Sans Serif", 16)
    checkBox2.Text = array(5)
    Me.Controls.Add(checkBox2)
    

按钮的处理

    Sub addToOrderButtonClicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Dim cb1 As Boolean = CheckBox.Name("cb1_ "sender.Name.Substring(4)) 
        'Substring to remove the fist 4 characters from the name of the sender button
        'Dim cb2 As Boolean = CheckBox.Name("cb2_ "sender.Name.Substring(4))

        MsgBox("You have selected button: " & sender.Name) '& CStr(cb1) & CStr(cb2)
    End Sub

array(0) 是项目的 ID(我现在使用占位符名称,它只是一个原型)

我目前能想出的解决方案是向复选框添加一个处理程序,该处理程序写入临时文件或全局变量 (ew),在 addToOrderButtonClicked 子中读取,但我觉得可能有更好的方法这样做的方法。

如有任何帮助,我们将不胜感激!

您可以使用 Controls.Find() 的递归选项按名称搜索控件,无论它在表单中的嵌套有多深:

Sub addToOrderButtonClicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim ID As String = sender.Name.Substring(4)
    Dim ctl1 As Control = Me.Controls.Find("cb1_" & ID, True).FirstOrDefault
    Dim ctl2 As Control = Me.Controls.Find("cb2_" & ID, True).FirstOrDefault
    If Not IsNothing(ctl1) AndAlso TypeOf (ctl1) Is CheckBox AndAlso Not IsNothing(ctl2) AndAlso TypeOf (ctl2) Is CheckBox Then
        Dim cb1 As Boolean = DirectCast(ctl1, CheckBox).Checked
        Dim cb2 As Boolean = DirectCast(ctl2, CheckBox).Checked
        MessageBox.Show("You have selected button: " & sender.Name & " " & cb1 & " " & cb2)
    End If
End Sub