简体   繁体   English

动态按钮未调用点击事件

[英]Dynamic Button not calling click event

I have a asp Table in my page and I create its contents from the code-behind. 我的页面中有一个asp表,我从后面的代码创建其内容。 For this particular TableRow I need to create a multiline textbox and a button, when I click a button I save the textbox content into my DB. 对于此特定的TableRow,我需要创建一个多行文本框和一个按钮,当我单击按钮时,将文本框内容保存到数据库中。 But my click function isn't getting called. 但是我的点击功能没有被调用。 Here's my code: 这是我的代码:

ContentPlaceHolder cont = new ContentPlaceHolder();
HtmlGenericControl br = new HtmlGenericControl();
HtmlGenericControl br2 = new HtmlGenericControl();
TextBox texto = new TextBox();
Button btnSalvarTexto = new Button();
btnSalvarTexto.ID = "btnSalvar";
btnSalvarTexto.Click += new EventHandler(btnSalvarTexto_Click);
btnSalvarTexto.CssClass = "botao";
btnSalvarTexto.Text = "Salvar";
cont.ID = "Placeholder";
texto.ID = "TextBoxObs";
texto.Width = 300;
texto.TextMode = TextBoxMode.MultiLine;
texto.Rows = 3;
br.InnerHtml = "<br><br><div style='width:300px;background-color:#fff;padding:15px;'>";
cont.Controls.Add(br);
cont.Controls.Add(texto);
cont.Controls.Add(btnSalvarTexto);
br2.InnerHtml = "</div>";
cont.Controls.Add(br2);
td2.Controls.Add(cont);
tr2.Cells.Add(td2);
TablePrecos.Rows.Add(tr2);

The event handler: 事件处理程序:

void btnSalvarTexto_Click(object sender, EventArgs e)
{
    //Update command here, this function doesn't even gets called, so it doesn't matter what it does
}

What's wrong with my code? 我的代码有什么问题? I've put a breakpoint in the btnSalvarTexto_Click function and it never reaches it. 我在btnSalvarTexto_Click函数中设置了一个断点,但从未实现。

EDIT: Ok, the function wich creates these controls is called CriarCapa, it's called in Page_LoadComplete like this: 编辑:好的,创建这些控件的函数称为CriarCapa,它在Page_LoadComplete这样调用:

 protected void Page_LoadComplete(object sender, EventArgs e)
 if (!IsPostBack)
 {
    CriarCapa();
 }

So yeah, I'm testing to see if it's not a postback. 是的,我正在测试是否不是回发。

You need to recreate the button on each page load, because it is being wiped out by the button being clicked and causing a post back. 您需要在每次页面加载时重新创建按钮,因为单击按钮会抹掉按钮,并导致回发。

The button causes a post back, which triggers the Page_Load event in the page lifecycle before the actual event handler. 该按钮导致回发,该回发会在实际事件处理程序之前在页面生命周期中触发Page_Load事件。 Since the button is dynamically created, when the page load happens and your code only builds the dynamic content the first time through, the button is not created nor is the event handler wireup for the click event. 由于该按钮是动态创建的,因此在页面加载发生并且您的代码仅在第一次构建动态内容时,不会创建该按钮,也不会创建click事件的事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM