CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2010
    Posts
    47

    Cycling through Controls in a Panel

    I have a panel on a form which contains both Radio Buttons and ComboBoxes. I thought this should work

    Code:
    Private Function CheckBoxesAllSet() As Boolean
      CheckBoxesAllSet = True
      For Each chkBox As CheckBox In Panel2.Controls
        If chkBox.Checked = False Then
          CheckBoxesAllSet = False
        End If
      Next
    End Function
    But I get error message: "Unable to cast object of type 'System.Windows.Forms.ComboBox' to type 'System.Windows.Forms.CheckBox'."

    Comments appreciated
    .

  2. #2
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,283

    Re: Cycling through Controls in a Panel

    I would suggest determining the type of the control first, before directly casting it. Some psuedo code would look like this :

    Code:
    Private Function CheckBoxesAllSet() As Boolean
      CheckBoxesAllSet = True
    Dim ct As Control
    
      For Each ct In Panel2.Controls
    If TypeOf ct Is CheckBox Then
        If ct.Checked = False Then
          CheckBoxesAllSet = False
        End If
      Next
    End If
    End Function
    I hope it helps!

  3. #3
    Join Date
    Aug 2010
    Posts
    47

    Re: Cycling through Controls in a Panel

    Yes, that is the way I did it! I was really hoping somebody knew how to do it in one shot but thanks anyway for replying!

    You can actually take it one stage further if you have something inside a container. This is something I wrote:

    Code:
    For Each cntA In frmCalledByFP.Controls 
        If TypeOf cntA is Panel then
          panPanel = CType(cntA, Panel)
          For Each cntB In panPanel.Controls  
            If TypeOf cntB is Button then
              If cntB.Name = "cmdContinue" then
                cmdButton = CType(cntB, Button) 
                cmdButton.Text = "Continue"
                frmCalledByFP.Show()
                'cmdButton.PerformClick  
                On Error GoTo 0
                Exit Sub
              End If 
            End If
          Next
        End If 
      Next
    Hope this helps somebody! Yes, I know that "On Error GoTo 0" is now a bit passe but I am converting a lot of code from VB6 ...
    .

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

Featured