CommandEventArgs Questions and Events

I created several buttons and attached an event handler to them as follows:

Button pgs = new Button();//Create New Topic pgs.Width = 20; pgs.Command += obtainTopicsPerPage_Click; pgs.CommandName = tPage.ToString(); pgs.Text = tPage.ToString(); btns.Add(tPage.ToString()); buttons.Add(pgs); } void obtainTopicsPerPage_Click(Object sender, CommandEventArgs e) { foreach (var item in tPages) { if (item.Key == e.CommandName) { foreach (var posts in item.Value) { posts.ExecuteAll(); } } } MyButtonTable(); } 

Now, when I click on the button, the event handler never starts. I check with the debugger, and when I click the button, there is only a postback, but it does not reach inside the funderoin eventhandler function

Update:

  void Page_PreInit(object sender, EventArgs e) { List<Button> btn=(List<Button>)ViewState["Buttons"]; foreach (var item in btn) { item.Width = 20; item.Command += obtainTopicsPerPage_Click; //resigning the eventhandlers from the begining item.CommandName = tPage.ToString(); item.Text = tPage.ToString(); } } 
+4
source share
1 answer

This often happens when creating buttons dynamically. When the page returns, the page no longer has buttons and therefore cannot bind them to event handlers.

The easiest solution is to make sure that you re-generate all the buttons in Page_Init each time the page loads.

+3
source

All Articles