Draw text on a Panel

13,906

The text isn't being drawn to panel1 because you need to refresh it.

Add this code to button1_Click, after you set drawText to true:

panel1.Refresh();

That will make the static text show up.

Share:
13,906

Related videos on Youtube

Bor
Author by

Bor

Updated on June 04, 2022

Comments

  • Bor
    Bor over 1 year

    OK, I fix everything, now is exactly what I want. I have a textBox1, panel1, and drawTexta (a button).

    When I click the button and choose a point in the panel, I want to draw the string from the textBox1.

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        using (SolidBrush br = new SolidBrush(Color.Red))
        {
            StringFormat sf = new StringFormat();
            sf.FormatFlags = StringFormatFlags.DirectionRightToLeft;
            e.Graphics.DrawString(textBox1.Text, this.Font, br, point1, sf);
        }
    }
    
    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
        point1 = new Point(e.X, e.Y);
    } 
    
    bool flag = false;
    Point point1 = new Point();
    
    private void drawTexta_Click(object sender, EventArgs e)
    { 
        flag = true;
        panel1.Refresh();
    }
    
    • GolezTrol
      GolezTrol about 11 years
      Wouldn't it be easier to use a textbox and only draw the text on the canvas afterwards?
    • Alvin Wong
      Alvin Wong about 11 years
      The only thing I know is that there is going to be a memory leak by SolidBrush.
    • Yatrix
      Yatrix about 11 years
      @AlvinWong .net handles garbage collection. It's still a good practice to use using, however.
    • Alvin Wong
      Alvin Wong about 11 years
      @Yatrix No, GDI+ resources need to be disposed properly (like putting it in a using block) because they are not GC-ed. dotnetfacts.blogspot.com/2008/03/things-you-must-dispose.htm‌​l
    • Bor
      Bor about 11 years
      @GolezTrol can you give me any further information about adding a textbox ? OnMouseDown creates a textbox or ? I added using as well
    • Yatrix
      Yatrix about 11 years
      @AlvinWong then thank you for teaching me something new.
  • Alvin Wong
    Alvin Wong about 11 years
    I just learnt that Refresh is a combination of Invalidate and Update. blogs.msdn.com/b/subhagpo/archive/2005/02/22/378098.aspx