Search code examples
c#asp.netcode-behindweb-controls

Dynamic control not showing up on page


This is relatively straight forward, but I'm obviously missing a step and cannot find support on resolving my issue.

I'm simply trying to append a dynamically created control to my page, but that is not happening. Here's a stripped down version of what I'm doing:

Button button = new Button();
button.Click += new EventHandler(btnTakeAction_Click);
button.Text = "Take Action";
button.ID = "btnTakeAction";
fullPayOnlyCoupon = string.Format(
    "<div>Some random text. I want my control to show up here: {0}</div>", button);

Assume that btnTakeAction_Click is valid. Also, I know this won't show the button properly, but instead just render it something like WebControl.Button. But that is the idea of what I'm looking for: the button to show up in a specific spot in the dynamically created markup within a string. From what I understand, you must add this button control to another pre-existing control that is already on the page. So I've tried this:

Button button = new Button();
button.Click += new EventHandler(btnTakeAction_Click);
button.Text = "Take Action";
button.ID = "btnTakeAction";
ControlOnAspxPage.Controls.Add(button);

But the ControlOnAspxPage does not render my dynamically created button.


Solution

  • Try using a Placeholder control:

    <asp:PlaceHolder
      EnableTheming="True|False"
      EnableViewState="True|False"
      ID="string"
      OnDataBinding="DataBinding event handler"
      OnDisposed="Disposed event handler"
      OnInit="Init event handler"
      OnLoad="Load event handler"
      OnPreRender="PreRender event handler"
      OnUnload="Unload event handler"
      runat="server"
      SkinID="string"
      Visible="True|False"
    />
    

    With:

    myButton = new HtmlButton();
    myButton.InnerText = "Button 2";
    PlaceHolder1.Controls.Add(myButton);