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.
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 -
ASPX
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.