Search code examples
c#asp.netevent-handlinghtmlwriter

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 HtmlTextWriter(sw);

Button btnOpenFile = new Button();
btnOpenFile.ID = "BtnOpenFile-" + additionalReadingFileID;
btnOpenFile.Text = "Open";
btnOpenFile.CssClass = "SettingsChangeButton";
btnOpenFile.Click += new EventHandler(OpenFileInLocation);
btnOpenFile.RenderControl(writer);

writer.Close();
sw.Close();
this.LitAdditionalReadingContent.Text = sb.ToString();

The methods being added to the click event is

protected void OpenFileInLocation(object sender, EventArgs e)
{
    //  Change Selected ID to this one
    Button clickedLink = (Button)sender;
    int fileID = Convert.ToInt32(clickedLink.ID.Replace("BtnOpenFile", ""));

    IRPBestPracticeTopicAdditionalReadingFile myOpenFile = new IRPBestPracticeTopicAdditionalReadingFile(fileID);
    System.Diagnostics.Process.Start(@myOpenFile.FilePath);
 }

This works when i add a button on the ASP page and assign the click event to the button on the page load method, but doesnt seem to register when i am assigning it to a dynamically created button being rendered via a literal.

Does anyone know why? And is there a simple solution to this problem? Thanks in advance.


Solution

  • 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>