Issue while iterating through User Controls in a Windows Form

Related searches

I am facing an issue while running through all the User Controls in my Windows form.

I am creating a Windows Form that has the following features:

  1. The Main form has 3 User Controls embedded in it
  2. The Main form also has a combo box. Selecting a particular value in the Combo box will bring the corresponding User Control to the front.
  3. Each User Control has two Check boxes as well as two Combo boxes.
  4. The User can summon each User Control through the Main Form's combo box and check the check boxes and/or modify the combo boxes inside each User Control
  5. Once this is done, there is a button, which on being pressed, executes the following code. This code is supposed to check which check boxes have been checked from every User Control, and execute some functionality :
private void button1_Click(object sender, EventArgs e)
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                {
                    foreach (Control ctl in c.Controls)
                    {

                        if (ctl is CheckBox && (ctl as CheckBox).Checked)
                        {
                            Indicator.Text = "It's in";
                        }
                    }
                }
            }
            //Some other code after this
         }

Here, I have included a Text Box called "Indicator" that shows whether the compiler has entered a particular "for" loop or "if" block. And I'm observing that the innermost "if" alone is not getting executed.

Could someone point out why exactly this is happening?

You need a recursive algorithm,

void ProcessControls(Control ctrlContainer) 
{ 
    foreach (Control ctrl in ctrlContainer.Controls) 
    { 
        if (ctrl is CheckBox && (ctrl as CheckBox).Checked)
        {
             Indicator.Text = "It's in";
        }
        if (ctrl.HasChildren) 
            ProcessControls(ctrl); 
    } 
}

Loop over a form's controls in C#, Then the Panel is in the form's Controls collection but the PictureBox For example, when you click this program's All button, the following It then uses the Controls collection's OfType method to loop through the form's Button controls, circles that are tangent to three given circles (Apollonius' Problem) in� Click the drop-down arrow on the Customers node, and choose Customize. Select the ComplexDataGridView from the list of Associated Controls in the Data UI Customization Options dialog box. Click the drop-down arrow on the Customers table, and choose ComplexDataGridView from the control list.

I do think you might be better off adding some functionality to your user control so it can describe the state of its own checkboxes rather than going digging inside it to find it and do logic. Generally in OO programming, when we encapsulate things within a class, we also provide general purpose accessors "visible to the outside" to describe the internal state of affairs, rather than letting external code interests go poking around inside class to find out what they want

At some point in time you've added these usercontrols to the form either directly in the designer, or programmatically. In the first case they will have their own name:

var u1 = usercontrol1.GetCheckboxStateArray();
var u2 = usercontrol2.GetCheckboxStateArray();

Etc

Or maybe you added them programmatically, in which case it would make sense to keep track of them in a list as you're adding them:

protected List<UserControl> _ucList = new List<UserControl>();
...
foreach(var result in somedatabasequery){
  var uc = new UserControl(result.Whatever);
  this.Controls.Add(uc);
  _ucList.Add(uc);
}

Then this list can be iterated. Sure you could argue that "well .Controls is a collection too, so why add them to another list when they're already in an accessible collection" - for the reasons you're here; .Controls is a general purpose description of the hierarchy of all controls on a form, it contains stuff we don't want and is hard to iterate. This List is purely and simply all and only the stuff we're interested in

As an aside, the UI you have described is atypical. The more usual way of hiding and showing controls under the selection of something that holds a bit of text would be a TabControl. It might be easier to loop through too, if you will persist with this "search for UserControls in a collection of controls" method - tabcontrols have tabpages, tabpages would probably have a .Controls that just contains your UserControl. The tabpage intrinsically takes care of showing and hiding controls as pages are clicked on which could simplify your code

[Solved] c# How to iterate a form's custom controls, c.FocusColour = Colors.Yellow; My question is: How can I iterate thru all the custom controls on the form to set the new properties, or� In my windows form I have a tab control with a few tab pages. Each tab page has some user controls and some .net controls such as datagrid, labels e.t.c. When I resize the windows forms the controls dont change their size and position. So if I reduce the size of window it hides half of the controls on my application.

Thanks to everyone for the answers. As it happens, the issue was hiding in plain sight, right under my nose. In each of the User Controls, I had placed the Checkboxes and Combo Boxes inside a Group Box. It completely slipped my mind, so much so that I didn't even mention them in my question.

Thus, as @Caius had suggested in the comments, the code wasn't functioning because I had not addressed the Group Box Container holding these Controls. Once I removed the Group Boxes (used only for aesthetic purpose), the code started functioning properly.

How to loop through the user controls - MSDN, I am having a simple WPF window with a stack panel and I named this panel says to use visual tree but I am always getting the count 0 when I am using I would not recommend looping through all the controls in your user control was developed using win forms in that we used to loop for each controls� That has already happend a few times to me while working in WPF. One of this issues I recently had, was that in Windows Forms it was easy to iterate over all the controls located within a form or container (GroupBox for example). In WPF, it obviously didn’t work that way >.< As an example, the following code in Windows Forms:

Iterate through controls on windows form - MSDN, If you only want to loop threw the controls within your usercontrol then True) While ctrl IsNot Nothing If TypeOf ctrl Is TextBox Then 'If the control is a help others who are looking for solutions to the same or similar problem. Ok so now it is a flickering problem with changing controls Size and Location while MainForm is resizeing. Every time user changes the Size of the main form all controls are dramaticaly flickering. Activating double buffering and some flags of "SetStyle" remove flickering only while Cursor is moving, but not while Resizeing the form.

Custom Controls in Visual C# .NET, Using the Login Validation User Control in a Windows Application. Format Mask Control When the publishing class raises an event, all the subscribed applications are notified. Loop through the mask, adding fixed characters as needed. You can enable default double buffering in your forms and authored controls in two ways. You can either set the DoubleBuffered property to true, or you can call the SetStyle method to set the OptimizedDoubleBuffer flag to true. Both methods will enable default double buffering for your form or control and provide flicker-free graphics rendering.

The simple user control displays customers' phone numbers in a standard phone-number format, by using a MaskedTextBox and setting the mask to a phone number. During this walkthrough, you will learn how to: Create a new Windows Forms Application. Add a new User Control to your project. Visually design the user control.

Comments
  • None of the CheckBoxes are cheked or the UserControl is not direct child of the Form (it's inside another container). Or it's controls are not. You can use a simple recursive method to get all of them. Or use the Controls collection Find() method. Or use a class that manages all your UserControls and knows it all about them.
  • Are you writing this in visual studio? Do you know how to use the debugger to step through the code one line at a time? Does your user control feature a panel, that the checkboxes are inside? I think you might have to add more levels of digging if so, but single stepping and inspecting the control hierarchy using the locals window would tell you pretty quickly
  • Controls can contain other controls. One solution is a recursive algorithm to find all the controls; see dotnetthoughts.net/…
  • It is good etiquette to +1 useful answers and finally accept the best answer.