Thiago Ruiz
Thiago Ruiz

Reputation: 162

Dynamic Button not calling click event

I have a asp Table in my page and I create its contents from the code-behind. 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. 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.

EDIT: Ok, the function wich creates these controls is called CriarCapa, it's called in Page_LoadComplete like this:

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

So yeah, I'm testing to see if it's not a postback.

Upvotes: 2

Views: 1812

Answers (1)

Karl Anderson
Karl Anderson

Reputation: 34846

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

Upvotes: 4

Related Questions