添加click事件通过文字呈现的动态按钮 [英] Adding a click event to a dynamic button rendered through a literal
问题描述
我有一个是通过一个ASP呈现一个动态按钮:文字
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();
方法被添加到Click事件是
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);
}
当我添加一个按钮,在ASP页上,并指定click事件在页面加载方法的按钮,但是似乎没有当我将其分配给一个动态创建的按钮被通过文字呈现给注册这个工作。
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.
的技巧是,你需要重新加载的动态控制回用相同的ID Page_Init。,否则,他们就会变得无效,和事件不会被解雇。
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>
这篇关于添加click事件通过文字呈现的动态按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!