Solved

C# foreach iteration

Posted on 2013-05-20
5
319 Views
Last Modified: 2013-05-20
Good day all,

I am not the worlds most experienced C# developer so please bear with me :)
Recently started to move projects over to .NET C#.

I have a very simple issue which I do not seem to understand.

I have a method that creates buttons and also another method that disposes them off.
But in the disposing method my foreach iteration seems to miss the last control everytime.

I am not sure as to why this would happen.
Two buttons gets created in dynamically no problem.
When running the DisposeButtons() method all except one button gets removed.

Please see my code - been on loooong day so perhaps I am overlooking something here.

Thanks in advance :)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            LoadButtons();
        }

        private void LoadButtons()
        {
            var top = 20;
            var verticalspace = 5;

            for (int x = 0; x < 2; x++)
            {
                top += top + verticalspace;

                Button b = new Button();
                b.Text = "button_" + x.ToString();
                b.Top = top;
                b.Left = 20;
                b.Name = "button_" + x.ToString();
                this.Controls.Add(b);
            }
        }

        private void DisposeButtons()
        {
            foreach (Control c in this.Controls)
            {
                if (c is Button) {
                    this.Controls.Remove(c);
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                LoadButtons();
            }
            else
            {
                DisposeButtons();
            }
        }
    }
}

Open in new window

0
Comment
Question by:Marius0188
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 29

Expert Comment

by:QPR
ID: 39182580
Could it be you have nested controls?
Have a look here

http://stackoverflow.com/questions/5794699/change-all-buttons-on-a-form
0
 

Author Comment

by:Marius0188
ID: 39182611
Hi QPR,

Thanks for the reply.
If I understand correctly nest control = controls within controls?

Nope - well not according to me.
All the buttons are explicitly added to the form this().

:)
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 39182640
When you remove the buttons you are modifying the Controls() collection, which messes up the for loop.

One solution is to iterate backwards:
        private void DisposeButtons()
        {
            int count = this.Controls.Count -1;
            for (int i = count; i >= 0; i--)
            {
                if (this.Controls[i] is Button)
                {
                    this.Controls.RemoveAt(i);
                }
            }
        }

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 39182645
You could also add those dynamic buttons to a class level List<Button>, then iterate over that and work with them that way.
0
 

Author Comment

by:Marius0188
ID: 39182661
Aaaah - I know it.
Something so simple. How would I have not thought about it.

Great Idle_Mind and thanks a lot for this.
I need sleep :)

Points awarded to you....
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
transaction in asp.net, sql server 6 46
Where is this file? 3 33
C# Windows app updating JSON file error. 9 38
c#, datatable, aspx 4 15
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question