使用VB.net,我有多个动态生成的复选框,我需要获取它们当前的检查状态

时间:2013-12-16 19:26:31

标签: vb.net visual-studio-2010 checkbox

我用Google搜索了一堆,找不到合适的解决方案。我有一个带有tabcontrol的VB.net 2010 .net4项目。我需要能够添加新标签,每个标签都有几个面板和几个按钮和复选框。然后我需要能够确定每个选项卡上每个复选框的状态。这一切都动态生成,但我无法弄清楚如何在每个新选项卡上获取复选框状态。我尝试使用addHandler,但我不知道如何获取特定复选框的值。这是我到目前为止的代码。

Public Class Form1
Public tabCount As Integer = 2

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles          Button1.Click
    Dim hwnd = addTab("new tab")
End Sub
Function addTab(name)

    Dim newPanel As New Panel
    Dim toolbar As New Panel
    Dim reconnect As New CheckBox

    'ADD TAB
    tabCount = tabCount + 1
    TabControl1.TabPages.Add(name & tabCount)

    'MAIN PANEL, BINDS WITH EXE
    newPanel.BackColor = Color.Black
    newPanel.Dock = DockStyle.Fill
    TabControl1.TabPages(tabCount - 1).Controls.Add(newPanel)

    'TOOLBAR
    ToolBar.BackColor = Color.White
    ToolBar.Width = Me.TabControl1.Width
    ToolBar.Height = 40
    ToolBar.Top = 0
    ToolBar.Left = 0
    ToolBar.AutoScroll = False
    newPanel.Controls.Add(ToolBar)

    'CHECKBOX
    reconnect.Text = "Reconnect"
    reconnect.ForeColor = Color.Black
    reconnect.Width = 180
    reconnect.Top = 10
    reconnect.Left = 10
    ToolBar.Controls.Add(reconnect)

    Return newPanel.Handle
End Function

End Class

2 个答案:

答案 0 :(得分:2)

在这两行之间:

reconnect.Left = 10
ToolBar.Controls.Add(reconnect)

添加以下内容:

AddHandler reconnect.CheckedChanged, AddressOf CheckBox_CheckedChanged

假设你在某处声明了这个:

Private Sub CheckBox_CheckedChanged(sender As Object, e As EventArgs)
  Dim chk As CheckBox = DirectCast(sender, CheckBox)
  If chk.Checked Then
    'checkbox was checked
  Else
    'checkbox was unchecked
  End If
End Sub

您应该能够DirectCast senderCheckBox并通过CheckBox(或任何其他财产)识别您的Text

注意:您不需要公共变量或其他类似的工具。

答案 1 :(得分:0)

'如果你想检查一个复选框。我们检查了事件

 If chkbx.Checked Then
    'Do what you want to do 
End If

希望它有所帮助