复选框数组 VB.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28529715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:48:38  来源:igfitidea点击:

Array of Checkboxes VB.NET

vb.netfor-loopcheckboxcontrols

提问by Navtik

I can now draw multiple checkboxes onto the form, however im not sure as to how I can check each checkbox indivdually to see whether it has been checked or not. This is the code that I am using to draw the checkboxes to screen.

我现在可以在表单上绘制多个复选框,但是我不确定如何单独检查每个复选框以查看它是否已被选中。这是我用来将复选框绘制到屏幕的代码。

    Dim data as String() = New String() { "testing", "testing2" }
    Dim offset = 10
    For Each cur In data
        Dim checkBox = New CheckBox()
        Me.Controls.Add(checkBox)
        checkBox.Location = New Point(10, offset)
        checkBox.Text = cur
        checkBox.Checked = True
        checkBox.Size = New Size(100, 20)
        offset = offset + 20
    Next

回答by Steve

To retrieve your checkboxes added dynamically you could loop over the Forms controls collection

要检索动态添加的复选框,您可以遍历 Forms 控件集合

For Each chk In Me.Controls.OfType(Of CheckBox)()
   if chk.Checked Then
      if chk.Name = "testing" Then
          ' code for testing.checked = true
      Else if chk.Name = "testing2" then
          ' code for testing2.checked = true
      End If
   End If
Next

回答by Andrew Morton

You can store references to the checkboxes in a List(Of Checkbox):

您可以在 List(Of Checkbox) 中存储对复选框的引用:

Option Infer On

Public Class Form1

    Dim theCheckBoxes As List(Of CheckBox)

    Sub SetUpCheckBoxes()
        theCheckBoxes = New List(Of CheckBox)

        Dim data As String() = New String() {"testing", "testing2"}
        Dim offset = 10
        For Each cur In data
            Dim cb = New CheckBox()
            cb.Location = New Point(10, offset)
            cb.Text = cur
            cb.Checked = True
            cb.Size = New Size(100, 20)
            Me.Controls.Add(cb)
            theCheckBoxes.Add(cb)
            offset = offset + 20
        Next

    End Sub

    ' an example of doing something with the list of checkboxes
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim count = 0
        For Each cb In theCheckBoxes
            ' do something with cb.Checked
            If cb.Checked Then
                count += 1
            End If
        Next

        If count = 1 Then
            MsgBox("There is 1 checked.")
        Else
            MsgBox("There are " & count.ToString() & " checked.")
        End If

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        SetUpCheckBoxes()

    End Sub

End Class

However, if you wanted to make it more general so that you could have more than one set of checkboxes and you could add them to the container control of your choice, you could make it more sophisticated and have a class which looks after a set of checkboxes. As an example:

但是,如果您想让它更通用,以便您可以拥有多个复选框,并且可以将它们添加到您选择的容器控件中,您可以使其更复杂,并有一个类来处理一组复选框。举个例子:

Option Infer On

Public Class Form1

    Dim myCheckboxes As Dictionary(Of String, CheckboxOrganiser)

    'TODO: Consider putting this CheckboxOrganiser class in its own file.
    Public Class CheckboxOrganiser
        Implements IDisposable

        Property Checkboxes As List(Of CheckBox)

        ' ########### some examples of what could be in this Class
        Sub ShowCheckedCount()
            Dim count = 0
            For Each cb In Checkboxes
                ' do something with cb.Checked
                If cb.Checked Then
                    count += 1
                End If
            Next

            If count = 1 Then
                MsgBox("There is 1 checked.")
            Else
                MsgBox("There are " & count.ToString() & " checked.")
            End If

        End Sub

        Sub ShowIfChecked(tagText As String)
            For Each cb In Checkboxes
                If cb.Tag.ToString = tagText Then
                    MsgBox(String.Format("{0} is {1}checked.", tagText, If(cb.Checked, "", "not ")))
                    Exit For
                End If
            Next

        End Sub
        ' ########### end examples

        ' dispose of the CheckBoxes and the references to them
        Sub Clear()
            If Me.Checkboxes IsNot Nothing Then
                For Each cb In Me.Checkboxes
                    cb.Parent.Controls.Remove(cb)
                    cb.Dispose()
                Next
                Me.Checkboxes.Clear()
            End If

        End Sub

        ' add the CheckBoxes to a container control
        Sub Display(target As Control)
            'TODO: check that target is a container control
            target.Controls.AddRange(Me.Checkboxes.ToArray())

        End Sub

        ' make a new list of CheckBoxes
        Sub New(left As Integer, top As Integer, data As String())
            Checkboxes = New List(Of CheckBox)
            Dim cbSize As New Size(100, 20)

            Dim offset = top
            For Each cur In data
                Dim cb = New CheckBox()
                cb.Location = New Point(left, offset)
                cb.Text = cur
                cb.Tag = cur
                cb.Checked = True
                cb.Size = cbSize
                Checkboxes.Add(cb)
                offset = offset + 20
            Next

        End Sub

        Sub New()
            Checkboxes = New List(Of CheckBox)

        End Sub

        ' We're trying to do this properly, so it is best to implement the code for .Dispose()...
#Region "IDisposable Support"
        Private disposedValue As Boolean ' To detect redundant calls

        ' IDisposable
        Protected Overridable Sub Dispose(disposing As Boolean)
            If Not Me.disposedValue Then
                If disposing Then
                    Me.Clear()
                End If
            End If
            Me.disposedValue = True
        End Sub

        ' This code added by Visual Basic to correctly implement the disposable pattern.
        Public Sub Dispose() Implements IDisposable.Dispose
            ' Do not change this code.  Put cleanup code in Dispose(disposing As Boolean) above.
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
#End Region

    End Class

    ' an example of getting rid of a set of CheckBoxes
    Private Sub bnRemoveTestCbs_Click(sender As Object, e As EventArgs) Handles bnRemoveTestCbs.Click
        myCheckboxes("tests").Dispose()

    End Sub

    ' an example of doing something with the checkboxes
    Private Sub bnCountThem_Click(sender As Object, e As EventArgs) Handles bnCountThem.Click
        myCheckboxes("shapes").ShowCheckedCount()

    End Sub

    ' inspect one checkbox in a collection
    Private Sub bnIsTriangleChecked_Click(sender As Object, e As EventArgs) Handles bnIsTriangleChecked.Click
        myCheckboxes("shapes").ShowIfChecked("Triangles")

    End Sub

    Sub Demo()
        ' use a Dictionary so that each CheckboxOrganiser can be referred to by a name
        myCheckboxes = New Dictionary(Of String, CheckboxOrganiser)

        ' create a set of checkboxes and name it "testing"...
        Dim data = New String() {"testing", "testing2"}
        myCheckboxes.Add("tests", New CheckboxOrganiser(10, 10, data))

        ' show them on the main Form
        myCheckboxes("tests").Display(Me)

        ' and another set of checkboxes...
        data = {"Triangles", "Squares"}
        myCheckboxes.Add("shapes", New CheckboxOrganiser(10, 20, data))

        ' we're going to add them to a GroupBox instead:
        Dim gb As New GroupBox With {.Left = 120, .Top = 20, .Width = 120, .Height = 80, .Text = "Shapes"}
        Me.Controls.Add(gb)
        myCheckboxes("shapes").Display(gb)

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Demo()

    End Sub


End Class

I started getting a bit carried away there, but I thought it worthwhile to show you how, with a bit more code to start off with, you can make other things simpler to use.

我开始有点不知所措,但我认为值得向您展示如何,通过更多的代码开始,您可以使其他东西更易于使用。

回答by Yamraj Pandya

Dim numberOfButtons As Integer
Dim buttons() as Button

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
    With buttons(counter)
       .Size = (10, 10)
       .Visible = False
       .Location = (55, 33 + counter*13)
       .Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
       'any other property
    End With
    '
next
End Sub

how to programmatically add-controls to a form in vb net

如何以编程方式向 vb net 中的表单添加控件