复选框和标签连接



我正在生成各种数量的复选框1-x和标签1-x:

WithEvents lb_cislozakazky As Windows.Forms.Label
WithEvents check_m As Windows.Forms.CheckBox
For i = 1 To x
        check_m = New Windows.Forms.CheckBox
        check_m.Name = "check_manual" & i
        check_m.Top = i * 20 - 19
        check_m.Left = 35
        check_m.Width = 20
        check_m.Height = 20
        Panel2.Controls.Add(check_m)   
 next

现在我想将一个复选框与一个标签连接起来。例如:当您选中chckbox1时,label1将变为红色

在将CheckStateChanged事件添加到复选框之前,您需要为它添加一个事件处理程序。然后在事件处理程序中,只需对名称中的i值进行操作,以使用相应的i值更改标签的属性。

WithEvents lb_cislozakazky As Windows.Forms.Label
WithEvents check_m As Windows.Forms.CheckBox
For i = 1 To 10
    check_m = New Windows.Forms.CheckBox
    check_m.Name = "check_manual" & i
    check_m.Top = i * 20 - 19
    check_m.Left = 35
    check_m.Width = 20
    check_m.Height = 20
    lb_cislozkzky = New Windows.Forms.Label
    select case (i)
        case 1 : lb_cislozakazky.Caption = "My caption for label 1"
        case 2 : lb_cislozakazky.Caption = "My caption for label 2"
        ...
    end select
    'do sizing positioning of label here:
    lb_cislozakazky.Name = "lb_cislozakazky" & i
    AddHandler lb_cislozakazky.CheckStateChanged, AddressOf CheckBox_CheckStateChanged
    Panel2.Controls.Add(lb_cislozakazky)
    Panel2.Controls.Add(check_m)   
next

Private Sub CheckBox_CheckStateChanged(sender as Object, e as EventArgs)
Dim index as integer
Dim msg as string
    if not integer.tryparse(((CheckBox)sender.Name.Remove(0, 15)), index) then index = -1
    if index <> -1 Then
        msg = "You pressed button " & index &", which is next to lb_cislozakazky_" & index & " and the label caption is: " & yourArrayOfLabelCaptions(index)
    Else
        msg = "Error - unable to determine index, check the name: " & (CheckBox)sender.Name & vbcrlf & " and try again!"    
    End If
    MessageBox.Show(msg)
end Sub

正如您所看到的,我使用您现有的伪代码来实现所有这些。您没有指定数组名称,因此您需要将yourArrayOfLabelCaptions替换为您的数组。

最新更新