Skip to content Skip to sidebar Skip to footer

Adding A Click Event To A Dynamic Button Rendered Through A Literal

I have a dynamic button which is being rendered through an ASP:Literal StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter writer = new H

Solution 1:

You can render a control as a literal. However, no event will be attached to those control. In other words, the click event will not be fired when the button posts back to server.

You want to add a control as a control using PlaceHolder or Panel.

The trick is you need to reload those dynamic control back in Page_Init with same ID. Otherwise, they'll become null, and event will not be fired.

Here is an example -

protected void Page_Init(object sender, EventArgs e)
{
    var btnOpenFile = new Button
    {
        ID = "BtnOpenFile-" + 1, 
        Text = "Open", 
        CssClass = "SettingsChangeButton"
    };
    btnOpenFile.Click += OpenFileInLocation;
    PlaceHolder1.Controls.Add(btnOpenFile);
}

ASPX

<%@ Page Language="C#" ... %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder runat="server" ID="PlaceHolder1" />
    </form>
</body>


Solution 2:

This is happening because you're not rebuilding the control on Load for the event to get bound. You need to cache enough information to rebuild the control on load and add it to the control hierarchy where it belongs so that the event can be bound and fired.


Post a Comment for "Adding A Click Event To A Dynamic Button Rendered Through A Literal"