Usually you do all your drawings in the paint event handler. If you want to do any update (if a user clicks on the panel for example) you have to defer that action: you store the required data (coordinates where the user clicked) and force a redraw of the control. This causes the paint event to be fired, where you can then draw things you stored before.
Another way would be (if you really want to draw outside of the 'panel1_Paint' event handler) to draw inside a buffer image, and copy the image to the controls graphics object in the paint event handler.
Update:
An example:
public class Form1 : Form
{
private Bitmap buffer;
public Form1()
{
InitializeComponent();
// Initialize buffer
panel1_Resize(this, null);
}
private void panel1_Resize(object sender, EventArgs e)
{
// Resize the buffer, if it is growing
if (buffer == null ||
buffer.Width < panel1.Width ||
buffer.Height < panel1.Height)
{
Bitmap newBuffer = new Bitmap(panel1.Width, panel1.Height);
if (buffer != null)
using (Graphics bufferGrph = Graphics.FromImage(newBuffer))
bufferGrph.DrawImageUnscaled(buffer, Point.Empty);
buffer = newBuffer;
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
// Draw the buffer into the panel
e.Graphics.DrawImageUnscaled(buffer, Point.Empty);
}
private void button1_Click(object sender, EventArgs e)
{
// Draw into the buffer when button is clicked
PaintBlueRectangle();
}
private void PaintBlueRectangle()
{
// Draw blue rectangle into the buffer
using (Graphics bufferGrph = Graphics.FromImage(buffer))
{
bufferGrph.DrawRectangle(new Pen(Color.Blue, 1), 1, 1, 100, 100);
}
// Invalidate the panel. This will lead to a call of 'panel1_Paint'
panel1.Invalidate();
}
}
Now the drawn images wont be lost, even after a redraw of the control, because it only draws out the buffer (the image, saved in the memory). Additionally you can draw things anytime a event occurs, by simply drawing into the buffer.