I need save image from specific child controls(Picturebox inside GroupBox), refer to this
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*/
}
}
CodePudding user response:
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