473,799 Members | 3,822 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# App: "Foreach" doesn't seem to loop through all controls on form

AHayes
10 New Member
_Background
I'm attempting to build a C# Windows application for work where I need to dynamically create and remove menu items (buttons). I've figured out how to dynamically create and (I think) remove these items, but I noticed that not all of my buttons are getting removed from the screen.

_The Code
This is a sample of how I'm CREATING the buttons:

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < arrButtonData.GetLength(0); i++)
  2. {
  3.         //Make new button               
  4.             Button btn_DynModify = new Button();
  5.  
  6.             //Initialize data.
  7.             btn_DynModify.Location = pntCurrentLoc;
  8.             btn_DynModify.Name = "btn_Modify_" + arrButtonData[i, 1];
  9.             btn_DynModify.BackColor = System.Drawing.Color.FromArgb(231, 241, 255);
  10.             btn_DynModify.Cursor = Cursors.Hand;
  11.             btn_DynModify.Width = 90;
  12.             btn_DynModify.Height = 90;
  13.             btn_DynModify.FlatStyle = FlatStyle.Flat;
  14.             btn_DynModify.FlatAppearance.BorderSize = 0;
  15.             btn_DynModify.Click += new System.EventHandler(btn_DynModify_Click);
  16.             btn_DynModify.Text = arrButtonData[i, 0];
  17.             btn_DynModify.TextAlign = ContentAlignment.BottomCenter;
  18.  
  19.             //Update location                
  20.             if (intCounter % intMaxCol == 0)
  21.             {
  22.                 pntCurrentLoc.X -= (btn_DynModify.Width + intOffsetX) * (intMaxCol - 1);
  23.                         pntCurrentLoc.Y += btn_DynModify.Height + intOffsetY;
  24.             }
  25.             else
  26.             {
  27.                         pntCurrentLoc.X += btn_DynModify.Width + intOffsetX;
  28.             }
  29.  
  30.  
  31.             //Add button to form and bring it to the front of the z-order stack.
  32.             Controls.Add(btn_DynModify);
  33.             btn_DynModify.BringToFront();
  34. }
  35.  
And this is how I'm attempting to remove the buttons:

Expand|Select|Wrap|Line Numbers
  1. //Clear pre-existing menu items.
  2. foreach (Control ctl in Controls)
  3. {
  4.     if (ctl.Name.StartsWith("btn_Modify_"))
  5.     {
  6.         Controls.Remove(ctl);
  7.     }
  8. }
  9.  

_What SEEMS to Be the Problem
I stepped through my code, specifically keeping an eye on the "foreach" loop each time. My assumption on what's going on is that it's not looping through ALL controls on the page, only some of them (seems to be only half of the buttons I want "removed" on screen are actually being removed when I call the "foreach" loop.


Anybody know why this might be happening?
Oct 3 '07 #1
3 11389
r035198x
13,262 MVP
_Background
I'm attempting to build a C# Windows application for work where I need to dynamically create and remove menu items (buttons). I've figured out how to dynamically create and (I think) remove these items, but I noticed that not all of my buttons are getting removed from the screen.

_The Code
This is a sample of how I'm CREATING the buttons:

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < arrButtonData.GetLength(0); i++)
  2. {
  3.         //Make new button               
  4.             Button btn_DynModify = new Button();
  5.  
  6.             //Initialize data.
  7.             btn_DynModify.Location = pntCurrentLoc;
  8.             btn_DynModify.Name = "btn_Modify_" + arrButtonData[i, 1];
  9.             btn_DynModify.BackColor = System.Drawing.Color.FromArgb(231, 241, 255);
  10.             btn_DynModify.Cursor = Cursors.Hand;
  11.             btn_DynModify.Width = 90;
  12.             btn_DynModify.Height = 90;
  13.             btn_DynModify.FlatStyle = FlatStyle.Flat;
  14.             btn_DynModify.FlatAppearance.BorderSize = 0;
  15.             btn_DynModify.Click += new System.EventHandler(btn_DynModify_Click);
  16.             btn_DynModify.Text = arrButtonData[i, 0];
  17.             btn_DynModify.TextAlign = ContentAlignment.BottomCenter;
  18.  
  19.             //Update location                
  20.             if (intCounter % intMaxCol == 0)
  21.             {
  22.                 pntCurrentLoc.X -= (btn_DynModify.Width + intOffsetX) * (intMaxCol - 1);
  23.                         pntCurrentLoc.Y += btn_DynModify.Height + intOffsetY;
  24.             }
  25.             else
  26.             {
  27.                         pntCurrentLoc.X += btn_DynModify.Width + intOffsetX;
  28.             }
  29.  
  30.  
  31.             //Add button to form and bring it to the front of the z-order stack.
  32.             Controls.Add(btn_DynModify);
  33.             btn_DynModify.BringToFront();
  34. }
  35.  
And this is how I'm attempting to remove the buttons:

Expand|Select|Wrap|Line Numbers
  1. //Clear pre-existing menu items.
  2. foreach (Control ctl in Controls)
  3. {
  4.     if (ctl.Name.StartsWith("btn_Modify_"))
  5.     {
  6.         Controls.Remove(ctl);
  7.     }
  8. }
  9.  

_What SEEMS to Be the Problem
I stepped through my code, specifically keeping an eye on the "foreach" loop each time. My assumption on what's going on is that it's not looping through ALL controls on the page, only some of them (seems to be only half of the buttons I want "removed" on screen are actually being removed when I call the "foreach" loop.


Anybody know why this might be happening?
The foreach loop works by iterating over a collection. You cannot modify a collection while you are iterating over it at the same time. You should convert Controls ToArray and then modify that array.
Oct 3 '07 #2
AHayes
10 New Member
The foreach loop works by iterating over a collection. You cannot modify a collection while you are iterating over it at the same time. You should convert Controls ToArray and then modify that array.

So, if I understand you correctly, the problem is occurring because I'm removing parts of the collection while trying to read it...which is causing it to "skip" over some of them.


That makes sense. Thanks.
Oct 3 '07 #3
Plater
7,872 Recognized Expert Expert
There is also a situation (at least in windows applications) where you would need to look at CHILD controls of the controls in Page.Controls.
like if you put a textbox in a groupbox and then put the groupbox on the page, you would only get the groupbox in the iteration, you would need to iterate through child controls of the groupbox to find the textbox.
Oct 3 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

32
4158
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
2
3233
by: recordlovelife | last post by:
So I am trying to display a title, date, and content of a wordpress blog. Word press provides nice drop in functions to get the job done with simple names like "the_title", and the "the_content" But on the homepage of a site, i wanted to truncate the content to like the first 75 characters and then put "..." (a perfect use of the smarty "truncate" modifier) and then give the visitor a link to read the whole article. But since "the_content" is a...
0
9543
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10488
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10237
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7567
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6808
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.