0

I'm using a foreach loop to create a list of users which all have a modify button. These are generated when they are loaded from the database.

For now the function only creates the modify button, but the problem is the .Click action:

foreach (XElement user in xml.Element("users").Elements())
        {
            Button modifyThisUser = new Button();
            modifyThisUser.Text = "Modify " + user.Attribute("LoginName").Value;
            modifyThisUser.Click += new EventHandler(ModifyThisUser_click);//only works when activated at Page_Load
            modifyThisUser.Attributes.Add("username", user.Attribute("LoginName").Value);
            form1.Controls.Add(modifyThisUser);
        }

This function creates the buttons.

When the function is called from the Page_Load the .Click action works, but if the function is triggert by a button the .Click won't work.

Why won't the .Click work if it is generated when the page is already loaded? The button itself shows and all the options work perfect, only the .Click isn't set. (so the EventHandler isn't fired when clicked)

How can I fix this problem?

Quispie
  • 948
  • 16
  • 30
  • I don't think you need to redefine the event handler, `Click += ModifyThisUser_Click` might be enough – Sayse Apr 09 '15 at 09:45
  • Where is your loop in page lifecycle? – Guanxi Apr 09 '15 at 09:47
  • @Sayse, I've already tried that, but it won't solve the problem. – Quispie Apr 09 '15 at 10:04
  • @Guanxi, what do you mean? The function is called from the page load without a problem, but I want it to be called by a button eventhandler. http://stackoverflow.com/questions/6187944/how-can-i-create-dynamic-button-click-event-on-dynamic-button – Quispie Apr 09 '15 at 10:05
  • if you see the link properly, there is one comment - You have to create button in OnInit method, otherwise event handler won't work. Thats why I am asking where is your loop in page lifecycle. Not everything of a page is called when you do a postback (such as action on button click) – Guanxi Apr 09 '15 at 11:27
  • I didn't undertand that part. I'm not able to find the init part. This is a webpage, is there a diffrence or a diffrent init location? – Quispie Apr 09 '15 at 12:32

0 Answers0