2

I am trying to draw a string using DrawString() method on a panel(panel1). I want this to happen when the form(Form1) loads. But that doesn't happen. But the string is drawn, if I use the same code(given below) in the click event handler for panel1. Where am I doing it wrong?

    private void Form1_Load(object sender, EventArgs e)
    {

        /*string rand = getRandomString();
        textBox1.Text = rand;*/
        string rand = "Hello";
        SolidBrush sbr = new SolidBrush(Color.Black);
        Graphics g = panel1.CreateGraphics();
        FontFamily fam = new FontFamily("Magneto");
        Font font = new System.Drawing.Font(fam, 24, FontStyle.Bold);
        g.DrawString(rand, font, sbr, new Point(20, 20));
    }   

2 Answers 2

5

The code you posted only gets executed once - when the form has a redraw triggered (such as getting another form over it, etc) it will dissapear. The same goes for your method in the button click event.

The way to draw onto the panel is as follows:

private void Panel1_Paint(object sender, PaintEventArgs e)
{

    var g = e.Graphics;
    /*string rand = getRandomString();
    textBox1.Text = rand;*/
    string rand = "Hello";
    using (var sbr = new SolidBrush(Color.Black))
    { 
        FontFamily fam = new FontFamily("Magneto");
        Font font = new System.Drawing.Font(fam, 24, FontStyle.Bold);
        g.DrawString(rand, font, sbr, new Point(20, 20));
    }

} 

The paint event for a control fires each time a redraw is required, so whatever you draw will not disappear unexpectedly.

2
  • Is there a way to invoke the Paint() event of the panel through a button-click? Like If I need a 'refresh' button to change the drawn string.
    – amulous
    Sep 21, 2012 at 10:04
  • I did this using the panel1.Invalidate() method and it worked fine. Thanks still
    – amulous
    Sep 21, 2012 at 10:20
4

This event happens before the form is displayed. So after you draw the text on the panel, panel is repainted and your changes are lost.

Even the text drawn later during Click event will disappear if the form is repainted, so you need to handle Panel control's Paint event and do your drawing there.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.