can not add elements in list (in C#)

Viewed 156

Below code I wanna add coordinates of mouse click to a list (I want click 4 times in different places in picturebox) and I want to store coordinates of mouse click in a list

But with this function only store one last coordinates in list (new coordinates replace with last coordinates and can not add to end of list). And my list have only one element always (need to have 4 coordinates for 4 times click in List) (after each click I have new coordinate in textbox3 and I used from List < Point > in list too with same result) thanks for your help

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        List<String> myPoints = new List<String>();
        textBox3.Text = e.X + " , " + e.Y;
        myPoints.Add(textBox3.Text);
     
    }
2 Answers

On every MouseDown you declare and initialize your list - so you need to move it outside of this method - so that it doesn't get destroyed after the scope of this function ends and it doesn't get overwritten by reinitialization.

When you declare a variable inside a scope - in this case a scope of pictureBox1_MouseDown method it gets destroyed once the function finishes.

Additionally, if you were to declare a variable outside a function but initialize it inside the function like so:

List<String> myPoints;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{   
    myPoints = new List<String>();
    textBox3.Text = e.X + " , " + e.Y;
    myPoints.Add(textBox3.Text);         
}

It would not be destroyed, but it's contents would be erased, so you'd end up with an empty list. So you need to do it like so:

List<String> myPoints = new List<String>();
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{   
    textBox3.Text = e.X + " , " + e.Y;
    myPoints.Add(textBox3.Text);         
}

You're creating a new list every time you call pictureBox1_MouseDown. Put it outside.

  List<String> myPoints = new List<String>();

  private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        
        textBox3.Text = e.X + " , " + e.Y;
        myPoints.Add(textBox3.Text);
     
    }
Related