我知道这个问题之前已经回答过,但我似乎无法得到一个可以与我想要的一起工作的答案,即能够检查我动态创建的复选框是否已被选中,我需要能够检查每个复选框单独。
这是我创建复选框的代码
Private Sub CreateCheckbox(ByVal x As Integer, ByVal y As Integer, text As String, ByVal id As Integer)
Dim btnYes As System.Windows.Forms.CheckBox
btnYes = New System.Windows.Forms.CheckBox
btnYes.AutoSize = True
btnYes.TabStop = True
btnYes.Name = "CheckBox" + id
btnYes.TabIndex = id
btnYes.Parent = Panel1
btnYes.Size = New System.Drawing.Size(81, 17)
btnYes.Location = New System.Drawing.Point(x, y)
btnYes.TabIndex = 1
btnYes.Text = text
Button1.TabIndex = Button1.TabIndex + 1
Me.Panel1.Controls.Add(btnYes)
End Sub
我需要类似的东西
for i as integer = 0 to id step 1
if checkbox(i).checked = true then
'Do Something
end if
next
最佳答案
您应该为动态创建的checkboxes
添加handler
,给定的代码将创建一个check box
,顺便说一句,它将添加checkedChanged
相同的事件处理程序。
Private Sub CreateCheckbox(ByVal x As Integer, ByVal y As Integer, text As String, ByVal id As Integer)
Dim btnYes As System.Windows.Forms.CheckBox
btnYes = New System.Windows.Forms.CheckBox
...............
...............
Me.Panel1.Controls.Add(btnYes)
'Now here add a common handler for your created checkbox
AddHandler btnYes.CheckedChanged addressOf CommonCheckedChangeHandler
End Sub
下面的过程将根据我们在上面添加的事件 (checkedchanged) 被调用。我们可以使用参数 sender
private sub CommonCheckedChangeHandler(ByVal sender As Object, ByVal e As System.EventArgs)
' This method will be invoked when your dynamically
' created check box's checked state got changed
End sub
编辑 1:
使用以下代码遍历面板
以检查您的复选框
For Each chkBox In Panel1.Controls.OfType(Of CheckBox)()
'Check here whether your check boxes are checked true/false
Next
编辑 2:
OfType 属于LINQ
,如果你不想上面的试试这个代码
for i as integer = 0 to id step 1
if Ctype(panel1.controls("CheckBox" & i), checkbox).checked = true then
'Do Something
end if
next
关于.net - 检查动态创建的复选框状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15516752/