Hello, there. I'm using Visual C#, creating a small game currently.
After
Graphics g = CreateGraphics();
g.DrawLine(new Pen(Color.White, 1), new Point(x, y), new Point(x, y);

How do i delete that line?

Dani AI

Generated

Short summary and recommended pattern (builds on , and )

What you drew with CreateGraphics is ephemeral: the OS will repaint the control and remove that drawing unless you do your painting inside the control's Paint pipeline. The reliable pattern is to keep a simple model (a list of lines), paint that model from your Paint/OnPaint handler, and update the model when you want to add or remove lines. Calling a repaint (Invalidate or Refresh) after changing the model causes the control to redraw from that model; removing a line is just removing it from the model and requesting a redraw.

Example skeleton (store lines, redraw in OnPaint, request redraw after changes):

// form-level storage
List<Tuple<Point,Point>> lines = new List<Tuple<Point,Point>>();

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e); // lets the background paint
    using (var pen = new Pen(Color.Black, 1))
    {
        foreach (var t in lines)
            e.Graphics.DrawLine(pen, t.Item1, t.Item2);
    }
}

void AddLine(Point a, Point b)
{
    lines.Add(Tuple.Create(a,b));
    Invalidate(); // request a repaint
}

void RemoveLineAt(int index)
{
    if (index >= 0 && index < lines.Count)
    {
        lines.RemoveAt(index);
        Invalidate();
    }
}

Troubleshooting and tips

  • Prefer Invalidate() (schedules paint) over forcing immediate painting unless you need synchronous behavior; Refresh forces an immediate repaint.
  • Enable double buffering (or SetStyle with OptimizedDoubleBuffer) on the control to avoid flicker when redrawing many items.
  • Dispose pens/brushes (use using) or reuse them for performance.
  • For many drawings, consider drawing into a Bitmap backbuffer (FromImage) and blit that, or call Invalidate(Rect) to redraw only a changed region.
  • Avoid CreateGraphics for persistent UI content; use it only for quick, transient effects.

Recommended Answers

All 4 Replies

public void ClearColor(PaintEventArgs e)
{
// Clear screen with teal background.
e.Graphics.Clear(Color.White);
}

public void ClearColor(PaintEventArgs e)
{
// Clear screen with teal background.
e.Graphics.Clear(Color.White);
}

So how do I call ClearColor?

Implement it via a button click handler or use a menu.

Found another solution: Refresh();

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.