I would like to reset a panel to its initial state. For example, I set an image as background, and I draw graphics on a part of the panel. I have to clear everything. How?
Asked
Active
Viewed 6.5k times
11
-
can you just abandon the old one and create assign `new Panle();` to the reference? – Bala R May 11 '11 at 04:04
-
1I suppose you are using the designer at compile time and that you want to "clear" the panel at runtime ? What other changes do you need to clear, more details would be nice. – Vincent B. May 11 '11 at 04:05
-
@Vincent B: I just need to clear the panel. I wrote a property "ClearPanel", inside it I tried \n 1. set the background = null \n 2. panel.Controls.Clear() ; but nothing works. – y_zyx May 11 '11 at 04:07
-
Rauf K: A property or a method ? Have you thought of calling suspendLayout() and resumeLayout(true) for the modification, are you sure your method is called ? – Vincent B. May 11 '11 at 04:14
-
Even panel.controls.clear() does not work means this is strange then – Developer May 11 '11 at 09:44
-
None of the proposed solution worked for me. – nu everest Jan 27 '16 at 19:30
-
Possible duplicate: *[Resetting a Windows Forms form's elements to an initialized state (C#/.NET)](https://stackoverflow.com/questions/337649/resetting-a-windows-forms-forms-elements-to-an-initialized-state-c-net)* – Peter Mortensen Nov 23 '22 at 22:24
5 Answers
22
You have to clear the panel first:
panel1.Controls.Clear();
Then call the initial form:
panel1.Controls.Add(orig_form);

Peter Mortensen
- 30,738
- 21
- 105
- 131

Ralph Calupas de Guzman
- 221
- 2
- 3
5
Use the following code to delete all graphics from the panel
panel1.Invalidate();
If there is something you need to add to panel's initial state then after you call invalidate you again have to set those things.
If the initial state of panels needs some graphics or data you can put that in panel's graphics event, so everytime invalidate is called your panel get the initial state with those items.

Marcello B.
- 4,177
- 11
- 45
- 65

Salman
- 1,380
- 7
- 25
- 41
3
Use the panel1.refresh();
command. It resets the panel to its initial state.

StormeHawke
- 5,987
- 5
- 45
- 73

Jakob
- 39
- 1
1
This was the only solution that worked for me:
private void button3_Click(object sender, EventArgs e) // Clear button
{
using (g = Graphics.FromImage(bmp))
{
g.Clear(Color.Transparent); // You can choose another color
// for your background here.
panel1.Invalidate();
}
}

Peter Mortensen
- 30,738
- 21
- 105
- 131

Filippe
- 31
- 2
0
This worked for me:
private void button1_Click(object sender, EventArgs e)//clear Data
{
panel1.Controls.Clear();
this.Refresh();
}

stateMachine
- 5,227
- 4
- 13
- 29

stdntuvmath
- 55
- 2