4

So i need to write simple "Minesweeper" game in asp.net (Only for learning purposes - it should be almost only javascript but anyway...)

I'm creating the game board dynamically at PageLoad, by creating a Table when each TableCell contains an ImageButton.

When i create each button, i'm adding to it's Click event my own event handler:

cellButton.Click += new EventHandler(tryOpenCell);

When i'm running the project, the game page loading exactly as expected, but when i click on any cell (which is an ImageButton as i said) the request goes back to the server code, but the button's Event Handler never invoked. Instead, the whole process just repeat itself, means regenerating the whole table game.

So my question is why my event handler never invoked?

Avi Shukron
  • 6,088
  • 8
  • 50
  • 84

1 Answers1

2

On Postback your button should be recreated and then it will handle the event..

protected void Page_Load(object sender, EventArgs e)
{
        ImageButton btn = new ImageButton();
        btn.ID = "Btn";
        btn.Click += new EventHandler(tryOpenCell);
        form1.Controls.Add(btn);
 }

Your button should be recreated in the page load event, before it can handle the event handler.

Off The Gold
  • 1,228
  • 15
  • 28
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
  • I guess that the most important thing is to specify the same ID when originally creating the button and at postback? – Avi Shukron May 17 '11 at 08:42
  • Your button should be recreated in page load event, before it handle the event hanlder. I have tested this thing at my end. As you know normally when you click button, page load event called before click event handler. – Muhammad Akhtar May 17 '11 at 08:43
  • Thanks! i think i had a gap in the matter of how event-deriven programming works on ASP.Net. Now it makes more sense. – Avi Shukron May 17 '11 at 08:49