0

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
5
  • If you want to create multiple checkboxes dynamically then you need to create them one-by-one (or using a loop). Commented Feb 15, 2015 at 18:48
  • @Steve I have updated the code which I am using to add checkboxes, the only problem now is how to check whether the check box has been checked or not. Commented Feb 15, 2015 at 19:04
  • You add the checkbox to the controls collection. To retrieve them just check that collection. However the real problem is what you want to do if the checkboxes are checked or not. If this is the same for every checkbox then you should not have a problem. Otherwise you need to add some if on the checkbox name Commented Feb 15, 2015 at 19:07
  • @Steve The checkboxes wont all be checked or all unchecked, also how can i check the collection? Commented Feb 15, 2015 at 19:12
  • Check (pun intended) the answer below. Commented Feb 15, 2015 at 19:13

3 Answers 3

2

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

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
Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

0

You can store references to the checkboxes in a 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.