Search code examples
c#pictureboxonpaint

repaint PictureBox with his information


When repaint my pictureboxes(from listUC) on a panel, i want to draw a ellipse and a string on each pictureBox. But nothing was drawn on the pictureBox.

I want to draw the string wich is stored in the uc.Name;

foreach (UseCase uc in listUC)
{
    ucNamePaint = uc.Name;
    //Create UseCaseBox    
    PictureBox useCaseBox = new PictureBox();
    useCaseBox.Name = uc.Index.ToString(); 
    Graphics g = useCaseBox.CreateGraphics();
    useCaseBox.Paint += new PaintEventHandler(OnPaint_picturebox);
}

Onpaint method:

private void OnPaint_picturebox(object sender, EventArgs e)
{
    var pb = sender as PictureBox;
    if (null != pb)
    {
        pb.BackColor = Color.Yellow;
        Graphics g = pb.CreateGraphics();
        Font drawFont = new Font("Arial", 10);
        int stringWidth = (int)g.MeasureString(ucNamePaint, drawFont).Width;
        int stringHeight = (int)g.MeasureString(ucNamePaint, drawFont).Height;

        if (selectedUC.Count() != 0)
        {
            Rectangle ee = new Rectangle(0, 0, stringWidth + 10, stringHeight + 10);
            using (Pen pen = new Pen(Color.Black, 2))
            {
                g.DrawEllipse(pen, ee);
            }
        }
        else 
        {
            Rectangle ee = new Rectangle(0, 0, stringWidth + 10, stringHeight + 10);
            using (Pen pen = new Pen(Color.Gray, 2))
            {
                g.DrawEllipse(pen, ee);
            }
        }

        StringFormat drawFormat = new StringFormat();
        drawFormat.Alignment = StringAlignment.Center;

        float emSize = pb.Height;
        g.DrawString(ucNamePaint, new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular),
           new SolidBrush(Color.Black), 7, 5);
    }
}

This code paints the picturebox yellow but nothing else is painted. Please explain me how to fix this!


Solution

  • The signature of the OnPaint method should really be:

    private void OnPaint_picturebox(object sender, PaintEventArgs e)
    

    then change this

    Graphics g = pb.CreateGraphics();
    

    to

    Graphics g = e.Graphics;
    

    Also it's definitely not a good idea to set paint related properties inside the paint handler. So, instead of

    pb.BackColor = Color.Yellow;
    

    use

    g.Clear(Color.Yellow);