Results 1 to 3 of 3

Thread: Remove custom controls [RESOLVED]

  1. #1

    Thread Starter
    <?="Moderator"?> john tindell's Avatar
    Join Date
    Jan 2002
    Location
    Brighton, UK
    Posts
    1,099

    Resolved Remove custom controls [RESOLVED]

    hey im trying to remove all my custom controls from my form, but not all of the are removed. i have to call my lear function a few times, depending on the number of controls. All of the controls are created at runtime and have different names.

    Code:
      		private void ClearResults()
      		{
      			foreach(Control c in this.pMain.Controls)
      			{
      				if(c is ResultsItem)
      				{
      #if DEBUG
     		 		Debug.WriteLine("Disposing of " + c.Name.ToString());
      #endif
     					c.Visible = false;
     					c.Dispose();
      				}
      			}
      		}
    Is there a better way to remove the controls from a form?

    Thanks
    Last edited by john tindell; Jan 28th, 2005 at 10:31 AM.

  2. #2
    Guru Aaron Young's Avatar
    Join Date
    Jun 1999
    Location
    Red Wing, MN, USA
    Posts
    2,177

    Re: Remove custom controls

    The issue you're running into is that you're altering the collection that you're enumerating, instead try something like this:
    Code:
          private void btnAddControls_Click(object sender, System.EventArgs e)
          {
             int count = new Random(DateTime.Now.TimeOfDay.Seconds).Next(49) + 1;
             
             this.pnlContainer.SuspendLayout();
             for( int i=0; i<count; i++ )
             {
                myControl control = new myControl();
                control.Name = "myControl" + i.ToString();
                control.Location = new Point((i % 4) * control.Width, (i / 4) * control.Height);
                this.pnlContainer.Controls.Add(control);
             }
             this.pnlContainer.ResumeLayout();
          }
    
          private void btnClearControls_Click(object sender, System.EventArgs e)
          {
             this.pnlContainer.SuspendLayout();
    
             for( int i=0; i<this.pnlContainer.Controls.Count; i++ )
                if( this.pnlContainer.Controls[i] is myControl )
                {
                   myControl control = (myControl)this.pnlContainer.Controls[i];
                   this.pnlContainer.Controls.RemoveAt(i);
                   control.Dispose();
                   i--;
                }
    
             this.pnlContainer.ResumeLayout();
          }

  3. #3

    Thread Starter
    <?="Moderator"?> john tindell's Avatar
    Join Date
    Jan 2002
    Location
    Brighton, UK
    Posts
    1,099

    Re: Remove custom controls

    cheers working great now. Thanks

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