Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# How to get child control in specific control

I need save image from specific child controls(Picturebox inside GroupBox), refer to this question, but GetAll() is from last to first return controls: ckBox8 -> ckBox3 -> ckBox1, how should save image from ckBox1 to ckBox8?

enter image description here

    public IEnumerable<Control> GetAll(Control control, Type type)
    {
        var controls = control.Controls.Cast<Control>();
        return controls.SelectMany(ctrl => GetAll(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
    }

    private void MyControlsTest()
    { 
        var c = GetAll(this, typeof(CheckBox));
        var ckBoxlist = c.OfType<CheckBox>().Where(ckBox => ckBox.Checked == true);
        foreach (var i in ckBoxlist)
        {
            MessageBox.Show(i.Name);
            /*Save PictureBox inside CheckBox if ckBox.Checked == true*/
        }
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because your controls have equivalent names, you can transform the name of the control you know, to find the control you want:

foreach(var g in this.Controls.OfType<GroupBox>()){  //'this' is the Form. If all your GroupBoxes are in some other panel/container, use that panel's name instead
  var cb = g.Controls[g.Name.Replace("gp", "ck")] as CheckBox;
  var pb = g.Controls[g.Name.Replace("gpBox", "pb")] as PictureBox;

  //PUT MORE CODE HERE e.g. if(cb.Checked) pb.Image.Save(...)
}

If cb/pb are null you’ll need to look into the hierarchy to see why; I can’t tell from a screenshot what the control nesting looks like. Indexing a ControlCollection by [some name] brings the first control that is a direct child member of the collection, but remember that controls exist in a tree – if you had a panel inside a groupbox then the checkbox is a child of the panel, not the groupbox (the panel is a child of the groupbox).

If things are deeply nested, you can look at ControlCollection.Find instead – there is a bool youcan specify to make it dig through all children. Note that it returns an array of controls

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading