在asp.net 4.5 c#中动态添加按钮点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16566551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add a button click event dynamically in asp.net 4.5 c#
提问by Higune
I have some questions to this post [1]: How can i create dynamic button click event on dynamic button?
我对这篇文章有一些问题 [1]:如何在动态按钮上创建动态按钮点击事件?
The solution is not working for me, I created dynamically an Button, which is inside in an asp:table controller.
该解决方案对我不起作用,我动态创建了一个 Button,它位于 asp:table 控制器中。
I have try to save my dynamic elements in an Session, and allocate the Session value to the object in the Page_Load, but this is not working.
我尝试将我的动态元素保存在会话中,并将会话值分配给 Page_Load 中的对象,但这不起作用。
Some ideas
一些想法
edit:
编辑:
...
Button button = new Button();
button.ID = "BtnTag";
button.Text = "Tag generieren";
button.Click += button_TagGenerieren;
tabellenZelle.Controls.Add(button);
Session["table"] = table;
}
public void button_TagGenerieren(object sender, EventArgs e)
{
TableRowCollection tabellenZeilen = qvTabelle.Rows;
for (int i = 0; i < tabellenZeilen.Count; i++)
{
...
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["table"] != null)
{
table = (Table) Session["table"];
Session["table"] = null;
}
}
}
采纳答案by Win
It is not a good practice to store every control into Session state.
将每个控件都存储到 Session 状态并不是一个好习惯。
Only problem I found is you need to reload the controls with same Id, when the page is posted back to server. Otherwise, those controls will be null.
我发现的唯一问题是当页面回发到服务器时,您需要重新加载具有相同 ID 的控件。否则,这些控件将为空。
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Label runat="server" ID="Label1"/>
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
private void LoadControls()
{
var button = new Button {ID = "BtnTag", Text = "Tag generieren"};
button.Click += button_Click;
PlaceHolder1.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Label1.Text = "BtnTag button is clicked";
}
Note: If you do not know the button's id (which is generated dynamically at run time), you want to save those ids in ViewStatelike this - https://stackoverflow.com/a/14449305/296861
注意:如果您不知道按钮的 id(在运行时动态生成),您希望ViewState像这样保存这些 id - https://stackoverflow.com/a/14449305/296861
回答by Raimond Kuipers
The problem lies in the moment at which te button and it's event are created in the pagelifecycle. Try the page_init event for this.
问题在于在页面生命周期中创建 te 按钮及其事件的那一刻。为此尝试 page_init 事件。
回答by Golda
Create Button in page load
在页面加载中创建按钮
Button btn = new Button();
btn.Text = "Dynamic";
btn.Click += new EventHandler(btnClick);
PlaceHolder1.Controls.Add(btn)
Button Click Event
按钮点击事件
protected void btnClick(object sender, EventArgs e)
{
// Coding to click event
}

