ASP.NET:问题与动态创建的控件的事件处理程序 [英] ASP.NET: Problem with event handlers for dynamically created controls

查看:87
本文介绍了ASP.NET:问题与动态创建的控件的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,动态创建的文本框。

I've got this problem with dynamically created TextBox.

当在pageLoad的创建文本框,它的TextChanged事件被解雇了。结果
但是,当我动态删除并重新创建文本框,该框TextChanged没有被解雇。

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.

这是code:

的.aspx
    
    

.aspx

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

</form>


的.cs

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

  protected void Page_Load(object sender, EventArgs e)
  {
    WriteRows();
  }

  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.Controls.Add(txt);
    tr.Controls.Add(tc);

    tc = new TableCell();
    tc.Text = txt.Text;
    tr.Controls.Add(tc);

    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()
  {
    Table1.Controls.RemoveAt(1);
    WriteRows();
  }
}

有没有人有一个解决方案,这样的事件总是被炒鱿鱼吗?

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

推荐答案

事件处理是由ASP.NET完成通过匹配了控件的ID和放大器;请求参数。在你的情况,)txtTextChanged(期间创建的文本框将有一个自动ID,因为你不指定任何明确的标识。该ID将文字改为活动期间调回。

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.

页面加载事件之后,ASP.NET将尝试找到这样的ID控制触发事件吧。显然ASP.NET将无法找到匹配,因为)的Page_Load(期间创建的文本框是不同的,并且将具有不同的ID。

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.

要解决这个问题:你的文本框指定一个明确的ID:

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

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

这篇关于ASP.NET:问题与动态创建的控件的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆