简体   繁体   English

ASP.NET把动态控件页上的反向搅乱事件

[英]ASP.NET putting dynamic controls on page in reverse messes up events

I have this weird problem when putting textboxes on the page in reverse. 将文本框反向放置在页面上时,我遇到这个奇怪的问题。 The whole event system is messed up. 整个事件系统搞砸了。 Changing one textbox fires TextChange on all textboxes. 更改一个文本框会在所有文本框上触发TextChange。 I can fix this by putting the controls in a list first and then call add while iterating trough the list in reverse. 我可以通过以下方式解决此问题:首先将控件放在列表中,然后在反向遍历列表时调用add。 But i just want to know why this fails. 但是我只想知道为什么这会失败。 Heres some code (.net 2.0) 继承人一些代码(.net 2.0)

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        InitFields();
    }

    private void InitFields()
    {
        int nrFields;
        //We have a static textbox called nrElements, this determines the number
        //of fields to initialize
        if (int.TryParse(nrElements.Text, out nrFields))
        {
            //Put all the dynamic fields on the screen in reverse order
            foreach(Control t in GetDynamicFields(nrFields))
            {
                //Calling Controls.Add works fine
                //Calling Controls.AddAt messes up the events
                //Try changing different textboxes
                plhFields.Controls.AddAt(0, t);
            }
        }
    }

    private IEnumerable<Control> GetDynamicFields(int nrFields)
    {
        for (int i = 0; i < nrFields; i++)
        {
            TextBox txtBox = new TextBox();
            txtBox.ID = string.Format("dynTextBox{0}", i.ToString());
            txtBox.AutoPostBack = true;
            txtBox.TextChanged += t_TextChanged;
            yield return txtBox;
        }
    }

    private void t_TextChanged(object sender, EventArgs e)
    {
        TextBox txtBox = sender as TextBox;
        if (txtBox != null)
            txtBox.Text = txtBox.Text + "Changed ";
    }
}

Try calling InitFields() on the Page_PreInit event rather than Page_Load. 尝试在Page_PreInit事件而不是Page_Load上调用InitFields()。

Or an alternative would be to override the CreateChildControls() method ( MSDN Article ), if you use CreateChildControls() you'll need to call EnsureChildControls() on the Page_Load method to make sure the CreateChildControls() method has been called before you try to access any controls which have been created within that method. 或替代将是覆盖的CreateChildControls()方法( MSDN文章 ),如果你使用的CreateChildControls(),你需要调用EnsureChildControls()在Page_Load方法,以确保的CreateChildControls()尝试之前方法被调用访问在该方法中创建的所有控件。

Always put dynamic controls in OnInit event. 始终将动态控件置于OnInit事件中。 Then viewstate serializer/deserializer will work. 然后,viewstate序列化器/反序列化器将起作用。 And you have to add controls on every request, not just in !IsPostBack. 而且,您必须为每个请求添加控件,而不仅仅是在!IsPostBack中。

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

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