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
}
}
}
VulpesPosted Dec 19, 2013, 8:11 PM
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:
Rob SobolPosted Dec 27, 2013, 9:20 AM
Works like a charm !
Problem solved !
WhooHoo !