CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Jan 2009
    Posts
    177

    Remove user control

    I have the following codes:

    Code:
       For Each ctrl As Control In Me.SplitContainer1.Panel1.Controls
                    If ctrl.GetType.ToString = "Adjustment.UI.ucSubApproval" Then
                        Me.SplitContainer1.Panel1.Controls.Remove(ctrl)
                    End If
                Next
    In my form, there is three user control, it able to remove the first and the third one, but it's not able to remove the second one. I believe it's caused by the for each statement where it will directly go to the third user control and skip the second after remove the first one.

  2. #2
    Join Date
    Aug 2009
    Location
    NW USA
    Posts
    173

    Re: Remove user control

    you may be able to use an index in reverse:

    for i as integer = Me.SplitContainer1.Panel1.Controls.Count - 1 to 0

  3. #3
    Join Date
    Aug 2009
    Location
    NW USA
    Posts
    173

    Re: Remove user control

    or create a List (of them) as you perform the test then itterate through your List to do the deleting

  4. #4
    Join Date
    Jan 2009
    Posts
    177

    Re: Remove user control

    Hi, I tried this:

    Code:
      For introw = Me.SplitContainer1.Panel1.Controls.Count - 1 To 0
                    If Me.SplitContainer1.Panel1.Controls(introw).GetType.ToString = "Adjustment.UI.ucSubApproval" Then
                        Me.SplitContainer1.Panel1.Controls.RemoveAt(introw)
                    End If
    
                Next

    It won't go into the loop and remove the controls. Something wrong?

  5. #5
    Join Date
    Jul 2008
    Location
    WV
    Posts
    5,362

    Re: Remove user control

    You need to tell it to go backwards else it will think you mean forward and there is nothing to do

    Code:
    For introw = Me.SplitContainer1.Panel1.Controls.Count - 1 To 0 Step -1
    If the Step is ommitted then it assumes Step +1
    Always use [code][/code] tags when posting code.

  6. #6
    Join Date
    Apr 2012
    Posts
    43

    Re: Remove user control

    Generally you shouldn't be altering collections you're iterating. Datamiser's suggestion of iterating in reverse will work but note he is using a For...Next loop, a For Each...Next cannot work for this. Mur16's suggestion of using another list is good to go too.

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