0

I am creating buttons programmatically in Android Xamarin (C#) like this:

for(int i = 0; i < 3; i++) {
    ...
    Button b = new Button(this);
    b.Click += delegate {
        processClick(i);
    };
    ...
}

the processClick method looks like this:

public void processClick(int i) {
    ... Log("i: " + i);
}

It successfully creates 3 buttons, but if I press any of them, the console log's number 3. The question is, how handle clicked events of programmatically created buttons?

poupou
  • 43,207
  • 6
  • 76
  • 172
Vilda
  • 1,593
  • 1
  • 18
  • 42

1 Answers1

3

This is called closure. Rewrite your for loop as follows:

for(int i = 0; i < 3; i++) {
    ...
    Button b = new Button(this);
    var j= i;
    b.Click += delegate {
        processClick(j);
    };
    ...
}

Also there is a good discussion on SO related to this topic.

Community
  • 1
  • 1
Ilya Luzyanin
  • 7,590
  • 4
  • 27
  • 48