ASP.NET: Problem with event handlers for dynamically created controls

I've got this problem with dynamically created TextBox.

When the TextBox is created in PageLoad, it's TextChanged event was fired. But when I dynamically delete and recreated the TextBox, the TextChanged was not fired.

This is the code:


<asp:Table ID="Table1" runat="server">
    <asp:TableCell ColumnSpan="2">Fixed content</asp:TableCell>



public partial class test : System.Web.UI.Page
  string myText = "a";

  protected void Page_Load(object sender, EventArgs e)

  private void WriteRows()
    TableRow tr = new TableRow();

    TableCell tc = new TableCell();
    TextBox txt = new TextBox();
    txt.Text = myText;
    txt.TextChanged += new EventHandler(txt_TextChanged); // Assign event handler

    tc = new TableCell();
    tc.Text = txt.Text;

    Table1.Controls.AddAt(1, tr);

  private void txt_TextChanged(object sender, EventArgs e)
    myText = ((TextBox)sender).Text;
    RedrawTable(); // Delete the row (incl. the TextBox) and rewrite it

  private void RedrawTable()

Does anyone have a solution so that the event is always fired?


Event handling is done by ASP.NET by matching up control's ID & the request parameters. In your case, the TextBox created during txtTextChanged() will have an auto ID because you don't specify any explicit ID. That ID will be posted back during the text changed event.

After page load event, ASP.NET will try to find a control with such ID to fire the event for it. Obviously ASP.NET won't be able to find the match because the TextBox created during Page_Load() is different and would have different ID.

To solve this: specify an explicit ID for your textbox:

TextBox txt = new TextBox();
txt.Text = myText;
txt.ID = "txtBox";

Need Your Help

My maven build fails when I try to include neo4j-rest-graphdb in my build

rest dependencies neo4j maven-3

When I try to build my project and include the Neo4j-rest-graphdb dependency the build fails. I have tried several different versions with the same result.

Form get's resent on refresh

php mysql forms page-refresh

Form get's resent on refresh, I had read about header("Location:my_page.php") unset($_POST), but I'm not sure where to place it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.