复选框和标签连接

时间:2015-10-09 12:58:29

标签: vb.net checkbox

我正在生成各种数量的盒子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会将颜色更改为红色。

1 个答案:

答案 0 :(得分:1)

在将event handler事件添加到面板之前,您需要为CheckStateChanged事件添加{{3}}。然后在事件处理程序中,只需对名称中的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替换为您的数组。