简体   繁体   中英

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?

在此处输入图像描述

    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*/
        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM