Question

Im trying to add buttons to a placeholder, each with an eventhandler to the same method.

        if (!this.IsPostBack)
        {

                foreach (Entry ent in results)
                {
                    HtmlButton btn = new HtmlButton();
                    btn.ServerClick += new EventHandler(resultSelected);
                    btn.InnerText = ent.name;
                    btn.ID = ent.ID.ToString();
                    PlaceHolder1.Controls.Add(btn);
                }
       }

1) The button is added to the page but when its clicked the method (resultSelected) is not called, only Page_Load again. And when it enters Page_Load the PlaceHolder is empty (the button is not displayed on the page). How do I accomplish what Ive tried to do?

2) How do I assign CSS classes to buttons created in this way?

Was it helpful?

Solution

It's quite common issue when you start working with ASP.NET for the first time - adding dynamic controls on server side.

  1. First thing is that You have to add those controls and assign eventhandler on every page request - on every postback as well. For proper event handling and restoring ViewState, you have to assign to them the same IDs and apply the same hierarchy.
  2. Controls needs to be added before Page Load event - most convinient would be adding them on in overriden CreateChildControls() method, which is fired on Postback before OnLoad method.
  3. Events are fired after OnLoaded method, so if you will create any control in for example OnPreRender/Render method - any event won't be fired.

This is most straightforward approach with some details skipped in my description. For more detailed information please read about ASP.NET Application Life Cycle.

As for the second part of your question, you can either use explicit styles setting with Style Property or it should be also possible to add class attribute using Attributes Property, but right now i'm guessing, cause i think HtmlButton doesn't have CssClass property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top