且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查控件是否包含面板

更新时间:2023-11-27 18:28:34

在按钮单击事件中,您正在创建一个控件,而不是将其添加到任何控件,然后检查另一个控件是否包含它。那么,答案总是会是错误。



您创建了一个控件实例,但从未将其添加到任何内容中,包括您尝试显示它的表单。控件不会自动创建时出现!



你的如果语句完全没用。你所要做的就是添加新控件实例到您要托管它的控件或表单的Controls集合,然后设置其ChildIn但是你想要dex。而已。无需检查。
In the button click event, you're creating a control, NOT adding it to anything, then checking to see if another control contains it. Well, that answer is ALWAYS going to be False.

You created an instance of a control but never added it to anything, including the Form you're trying to display it on. The control doesn't automatically show up when created!

Your if statement is completely useless. All you have to do is just add the new control instance to the Controls collection of the control or form you want to host it and then set its ChildIndex however you want. That's it. Nothing to check.


var myPanel = new Panel() {new Size(50, 50), new Point(100,100)};
if ( ! ( controls.Contain(myPanel) ) {





答案是新面板在添加之前永远不会出现在Controls集合中。每个对象,而不仅仅是控件,在创建时都会被赋予一个唯一的ID。所以newing一个对象将永远是您需要做的是检查对象类型以查看集合中是否已存在面板类型。类似于(未选中):



The answer is the "new panel" will always never be in the Controls collection before it is added. Each and every object, not just controls, is given a unique ID on creation. so "newing" an object will always be false. What you need to do is to check the "type of object" to see if there is already a "panel type" in the collection. something like (unchecked):

if (!controls.Any(x => x is Panel))
{
    var myPanel = new Panel() {new Size(50, 50), new Point(100,100)};
    controls.Add(myPanel);
    controls.SetChildIndex(myPanel, 0);
}