如何检查控件是否包含面板 [英] How to check controls contain panel or not

查看:66
本文介绍了如何检查控件是否包含面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

如何检查form.controls是否包含一个面板



i我这样做的代码,当我如果面板不在表单控件的容器上,则单击按钮'A'



然后面板将添加到窗体的控件中

否则面板将被处置如果它已经在控件上



这是我试过的结果是

当我点击按钮时,它继续添加一个新的控制层



我尝试过:



hello,
how to check form.controls contain a panel or not

i am doing the code in this way, when i clicked on button 'A'
if the panel is not on the container of the form's control.
then the panel will be added to the control of the form
else the panel will be dispose if it is already on the control

this is what i have try and the result is
when i click on the button, it keep on adding a new layer of control

What I have tried:

var myButton = new Button {new Size (50, 50), new Point(0,0)};
// add myButton to form.controls
myButton.mouseClick += buttonClicked;
controls.Add(myButton);

private void buttonClicked(object sender, eventArgs e){
var myPanel = new Panel() {new Size(50, 50), new Point(100,100)};
if ( ! ( controls.Contain(myPanel) ) {
controls.Add(myPanel);
controls.SetChildIndex(myPanel, 0);
}
else {
controls.RemoveAt(0);
myPanel.Dispose();
}
}

推荐答案

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



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



你的如果语句完全没用。你所要做的就是添加新控件实例到您要托管它的控件或表单的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);
}


这篇关于如何检查控件是否包含面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆