這個問題在這里已經有了答案: 如何通過“字串名稱”獲取控制元件屬性? (6 個回答) 昨天關閉。
我正在為學校開展一個專案,該專案利用咖啡館的選單。長話短說,我有一些代碼通過資料庫運行,并為每個條目向螢屏添加幾個新元素,包括兩個復選框和一個按鈕
創建時按鈕的名稱是“btn_”,然后是產品的ID,兩個復選框分別標記為“cb1_”和“cb2_”以及ID。我想要的預期行為是當按下按鈕時,讀取與按鈕具有相同 ID 名稱的兩個復選框值。
我有代碼:
創建按鈕/框
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 子中讀取,但我覺得可能有更好的方法來做到這一點。
任何幫助將不勝感激!
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/366495.html
標籤:网络
