Вопрос

I create some picture box dynamic, but i dont know how to make a individual action on click.

PictureBox[] app=new PictureBox[file.Length];
int i = 0, prev=20;
foreach(string element in file)
{
    app[i] = new PictureBox();
    app[i].BackgroundImage = Image.FromFile(element.Remove(element.Length - 3) + "png");
    app[i].Location = new Point(prev, 85);
    app[i].Size = new Size(100, 100);
    app[i].Name = "test" + i;
    app[i].Click += new EventHandler(run(element, dir));

    this.Controls.Add(app[i]);

    i++; 
    prev += 20;
}

private void run(string element, string dir)
{
      MessageBox.Show(element);
}

So how can I do that. Please help! Thanks!

Это было полезно?

Решение 2

Try to avoid using delegates/functions within a foreach loop, and if you do, use a copy of the object, not the variable in the loop statement.

var elementCopy = element;
...
app[i].Click += (sender,evt) => run(elementCopy,dir);

If you use the element directly, there is a chance it will always use the last element in the enumerable for the delegate

Edit: Refer to this: Using the iterator variable of foreach loop in a lambda expression - why fails?

It explains why you should do what I said more in-depth.

Другие советы

Is this what you want?

app[i].Click += (sender, args) => { MessageBox.Show(element);};

try this

app[i].Click += (s, e) => { run(element,dir); };
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top