Home > Enterprise >  i have a problem to add elements in list (in C#)
i have a problem to add elements in list (in C#)

Time:09-22

i am a beginner, with this 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 (i 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);
     
    }

CodePudding user response:

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);         
}

CodePudding user response:

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);
     
    }
  •  Tags:  
  • c#
  • Related