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
- for (int i = 0; i < arrButtonData.GetLength(0); i++)
- {
- //Make new button
- Button btn_DynModify = new Button();
- //Initialize data.
- btn_DynModify.Location = pntCurrentLoc;
- btn_DynModify.Name = "btn_Modify_" + arrButtonData[i, 1];
- btn_DynModify.BackColor = System.Drawing.Color.FromArgb(231, 241, 255);
- btn_DynModify.Cursor = Cursors.Hand;
- btn_DynModify.Width = 90;
- btn_DynModify.Height = 90;
- btn_DynModify.FlatStyle = FlatStyle.Flat;
- btn_DynModify.FlatAppearance.BorderSize = 0;
- btn_DynModify.Click += new System.EventHandler(btn_DynModify_Click);
- btn_DynModify.Text = arrButtonData[i, 0];
- btn_DynModify.TextAlign = ContentAlignment.BottomCenter;
- //Update location
- if (intCounter % intMaxCol == 0)
- {
- pntCurrentLoc.X -= (btn_DynModify.Width + intOffsetX) * (intMaxCol - 1);
- pntCurrentLoc.Y += btn_DynModify.Height + intOffsetY;
- }
- else
- {
- pntCurrentLoc.X += btn_DynModify.Width + intOffsetX;
- }
- //Add button to form and bring it to the front of the z-order stack.
- Controls.Add(btn_DynModify);
- btn_DynModify.BringToFront();
- }
Expand|Select|Wrap|Line Numbers
- //Clear pre-existing menu items.
- foreach (Control ctl in Controls)
- {
- if (ctl.Name.StartsWith("btn_Modify_"))
- {
- Controls.Remove(ctl);
- }
- }
_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?