[英]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?我需要从特定的子控件(Picturebox inside GroupBox)保存图像,参考这个问题,但是GetAll()是从最后到第一个返回控件:ckBox8 - > ckBox3 - > ckBox1,应该如何将图像从ckBox1保存到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;如果 cb/pb 是
null
,您需要查看层次结构以了解原因; 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).通过
[some name]
索引 ControlCollection 会带来作为集合的直接子成员的第一个控件,但请记住控件存在于树中 - 如果您在组框内有一个面板,那么复选框是面板的子项,而不是组框(面板是组框的子项)。
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.如果事物嵌套很深,您可以改为查看ControlCollection.Find - 您可以指定一个 bool 来使其遍历所有子项。 Note that it returns an array of controls
请注意,它返回一个控件数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.