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?

2
  • Classical closures. Use var j= i; inside for-loop and use processClick(j); Commented Aug 10, 2014 at 19:33
  • You mean: b.Click += delegate { int j = i; processClick(j); }; ? I've tried that and it didn't work. Commented Aug 10, 2014 at 19:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I did and it still doesn't work. It still logs number 3;
Sorry, my bad. I put the var j = i; in the delegate. Solved. Thanks.
That's my plan, but I can do that in 8 minutes.
Oh, sorry, didn't know about the limit :) Good luck!
Could you elaborate on the issue (e.g. 'closure') or at least provide references to good reading material?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.