2
Answers

WinApp not displaying picture box until button pressed...

Rob Sobol

Rob Sobol

11y
1.1k
1

Easy question for someone.....in the code below, why does pictureBox1 not display the rectangle as coded in the Form1 routine, but when I press the Button1, it appears?

    I wrote this test program because I have a program where I have a pictureBox and a gridView in a TabControl.  I bind the gridView and draw in the pictureBox when the form loads, but when I click on the tab, the gridView displays the data, but the pictureBox is empty. If I re-draw in the picturebox or rebind the gridview based on a button click, all gets displayed perfectly. 

  Am I using the wrong function to create the rectangle? Should I be using some Drawxxx instead of CreateGraphics?

 Thank you in advance for your time and expertise in helping on this matter. Beers on me !

Rob

namespace WindowsFormsTestRectangle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Rectangle r = new Rectangle(2, 2, 20, 10); //left,top,width,heigth
            pictureBox1.CreateGraphics().FillRectangle(Brushes.Red, r);    //nothing gets displayed
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Rectangle r = new Rectangle(2, 2, 20, 10); //left,top,width,heigth
            pictureBox1.CreateGraphics().FillRectangle(Brushes.Red, r);    //works fine
        }
    }
}

Answers (2)
0
Vulpes
NA 98.3k 1.5m 11y
The form's constructor runs before the form has loaded.

When the form loads, the Paint events for the form and its controls fire. Unfortunately, these events erase anything that has been drawn with a Graphics object derived from the CreateGraphics() method and so you don't see it.

Check this link for confirmation:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.creategraphics(v=vs.110).aspx

Incidentally, when you use CreateGraphics, you should always call Dispose() on the Graphics object to get rid of the underlying unmanaged resources. So I'd change your code to this:

        private void button1_Click(object sender, EventArgs e)
        {
            Rectangle r = new Rectangle(2, 2, 20, 10); //left,top,width,heigth
            Graphics g = pictureBox1.CreateGraphics();
            g.FillRectangle(Brushes.Red, r);
            g.Dispose();
        }
Accepted
0
Rob Sobol
NA 9 4.3k 11y


Works like a charm !

Problem solved !

WhooHoo !