Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
I am working on a drawing project. In the following code I handle new points in a temporary list and when mouseup event raised these points copied another list that handles all point lists.But when temporary list cleared, it is cleared from points list at the same time. So points list is always empty. How can it be fixed?

List<List<Point>> points = new List<List<Point>>();
List<Point> tempPoints = new List<Point>();
bool startDrawing;

public Form1()
{
    InitializeComponent();
    this.Paint += Form1_Paint;
    this.MouseMove += Form1_MouseMove;
    this.MouseDown += Form1_MouseDown;
    this.MouseUp += Form1_MouseUp;
}

void Form1_MouseUp(object sender, MouseEventArgs e)
{
    startDrawing = false;
    points.Add(tempPoints);
    tempPoints.Clear();
}

void Form1_MouseDown(object sender, MouseEventArgs e)
{
    startDrawing = true;
}

void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (startDrawing)
    tempPoints.Add(e.Location);
}

void Form1_Paint(object sender, PaintEventArgs e)
{
    foreach (List<Point> list in points)
    {
        if (list.Count >= 2)
            e.Graphics.DrawLines(Pens.Red, list.ToArray());
    }
    if (tempPoints.Count >= 2 & startDrawing)
    {
        e.Graphics.DrawLines(Pens.Red, tempPoints.ToArray());
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.Invalidate();
}
Posted

The problem is you are not adding the points themselves to the list but instead you are adding the whole temp list. The same list of points that you clear afterwards. Do not clear the temp list, create a new list instead:
C#
void Form1_MouseUp(object sender, MouseEventArgs e)
{
    startDrawing = false;
    points.Add(tempPoints);
    // tempPoints.Clear(); - no, this clears the list you just added to points
    tempPoints = new List<Point>(); // yes, create a new list to store the new points
}
 
Share this answer
 
v2
Comments
Amt-Coder 6-Sep-15 17:21pm    
That works great! Thanks.
Arasappan 7-Sep-15 2:06am    
nice.. 5ed
When you add tempPoints to another list it just add the reference so you need to first clone it before adding it to points. See below

C#
List<Point> tempPoints1=tempPoints.Select(point=> (Point)point.Clone()).ToList()

points.Add(tempPoints1);
 
Share this answer
 
Comments
Tomas Takac 6-Sep-15 17:09pm    
This is nonsense. Point is a struct. Why would you (explicitly) clone a struct? It doesn't even implement ICloneable. Most important: structs are cloned/copied all the time, that's by design.
Amt-Coder 6-Sep-15 17:23pm    
Tomas is right. It gives an debug error because of Point doesnt support Clone method.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900