Results 1 to 3 of 3

Thread: Checkbox Array

  1. #1

    Thread Starter
    New Member
    Join Date
    Aug 2010
    Posts
    1

    Unhappy Checkbox Array

    Please help, ugh

    I recently converted from VB6.0 to .Net 2005 and quickly realized control arrays are no longer used. In my larger project I create 50 check boxes on form load and want to take action on a check changed event when a user selects one of the check boxes.
    Can someone please let me know how to reference the checkboxes once they're created.

    Here is s simplified version of my code

    Thank you


    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    Dim CheckBox As New CheckBox()


    CheckBox.Text = "Checkbox1"
    CheckBox.Location = New Point(100, 50)
    CheckBox.Size = New Size(95, 45)
    Me.Controls.Add(CheckBox)


    End Sub

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,420

    Re: Checkbox Array

    you can use an array to reference your checkboxes:

    vb Code:
    1. dim checkboxes(49) as checkbox
    2.  
    3. Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    4.  
    5.     for x as integer = 0 to 49
    6.         checkboxes(x) = New CheckBox
    7.         checkboxes(x).Text = "Checkbox" & (x + 1).tostring
    8.         checkboxes(x).Location = 'etc
    9.         checkboxes(x).Size = 'etc
    10.         Me.Controls.Add(checkboxes(x))
    11.     next
    12.  
    13. End Sub

  3. #3
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    Re: Checkbox Array

    It's true that you can store the checkboxes in an array, but since you still need to add code for handling the CheckedChanged event and you always get a reference to the sender object in an event this is actually not necassary.
    Code:
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        For i As Integer = 0 to 49
          Dim checkBox As New CheckBox
          'checkBox.Size = 'blah blah....
          Me.Controls.Add(checkBox)
          AddHandler checkBox.CheckedChanged, AddressOf CheckBox_CheckedChanged
        Next
    End Sub 
    
    Private Sub CheckBox_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim checkBox As CheckBox = CType(sender, CheckBox)
        'Now you have a reference to the checkbox that was just checked.
    End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width