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,413
  • 6
  • 77
  • 174
Vilda
  • 1,675
  • 1
  • 20
  • 50

1 Answers1

4

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,910
  • 4
  • 29
  • 49