Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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();
}
}
Posted
Updated 5-Sep-17 17:08pm
v2

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.
 
Share this answer
 
C#
var myPanel = new Panel() {new Size(50, 50), new Point(100,100)};
if ( ! ( controls.Contain(myPanel) ) {


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):
C#
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);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900