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));
}
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
Clickevent will disappear if the form is repainted, so you need to handle Panel control’sPaintevent and do your drawing there.