0

I have create a ListView and get a data from a ListView to draw a rectangle. The ListView items count is always change with unknown count and also the x and y too. My ListView will be like this :

Subitem[0].Text || Subitem[1].text
500                100
100                200
++                 ++

By Subitem[0] is X ,Subitem[1] is Y
And now I have create a code to draw the rectangle like this:

private void Draw_Tick(object sender, EventArgs e)
{
   this.Invalidate();
   Pen p = new Pen(Color.Red);
   SolidBrush sb = new SolidBrush(Color.Red);
   Graphics g = PaintingPanel.CreateGraphics();
   for (int i = 0; i < ListView1.Items.Count + 1; i++)
      {
         p.Width = 3;
         g.SmoothingMode = SmoothingMode.HighSpeed;
         g.InterpolationMode = InterpolationMode.Low;
         g.PixelOffsetMode = PixelOffsetMode.HighSpeed;

         Rectangle rectf = new Rectangle(X.Split(',')[i],Y.Split(',')[i], 50, 75);
         g.DrawRectangle(p,rectf);     
      }
}

Add the X and Y to Array

Public static string X;
Public static string Y;

for (int i = 0; i < ListView1.Items.Count + 1; i++)
            {
                List<string> ls = new List<string>();


                foreach (ListViewItem item in ListView1.Items)
                {
                    ls.Add(item.SubItems[0].Text);

                }
                X = string.Join(",", ls);
            }


for (int i = 0; i < ListView1.Items.Count + 1; i++)
            {
                List<string> ls2 = new List<string>();


                foreach (ListViewItem item in ListView1.Items)
                {
                    ls2.Add(item.SubItems[1].Text);

                }
                Y = string.Join(",", ls2);
            }

But my point is I have used this.Invalidate() to clear the drawing and create a new drawing because the data changed. My question is how can I just move the rectangle instead of using this.invalidate to clear the drawing (Because its kind of flashing when this.Invalidate();.

  • 2
    CreateGraphics is almost always a mistake. Use the paint event and use the graphics from that parameter. Use `e.Graphics.Clear(yourColor);` Search for DoubleBuffered panels to avoid the flicker. – LarsTech Feb 01 '19 at 18:13
  • 1
    Panels by default are not double-buffered. Flicker goes away when you make them.. [DoubleBuffered](https://stackoverflow.com/questions/44185298/update-datagridview-very-frequently/44188565#44188565) - Anything drawn with control.CreateGraphics will not persist, which may be right or wrong.. - Also: You are leaking Pens and Brushes. Use the system versions (Pens.Red, Brushes.Red) or use a `using` clause! – TaW Feb 01 '19 at 19:04

0 Answers0