It's not a good practice to use Graphics
property anywhere other than Paint
event. Because you don't wanna lose what you've painted after a refresh, so you must paint them whenever needed, that is in Paint
event. So you have two choices:
First Create an Image
, get Graphics
from the image and draw your items to it, then set BackGroundImage
property of panel to this image. This way you don't mess with painting and give it to the control itself :)
Second Store the data needed for drawing rectangles in some variables in scope of the form. You may use a List
of Rectangle
s and Add
to them on each click, then draw them in Paint
event whenever needed:
private List<Rectangle> myrects=new List<Rectangle>;
private void childPanel_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.FillRectangles(Brushes.Red, myrects.ToArray());
}
Remember to include this in child panel if you use the scrolling trick you mentioned