0

ボタンを押したときにテキストボックスを生成しようとしているので、これは onclick のコードです

protected void Add_TextBoxes(object sender, EventArgs e)
        {
            int index =  int.Parse(ViewState["pickindex"].ToString());
            TextBox MyTextBox = new TextBox();
            MyTextBox.ID = "tbautogenerated"+index.ToString();
            MyTextBox.Text = "tbautogenerated" + index.ToString();
            MyTextBox.Width= 250;
            MyTextBox.MaxLength = 128;
            MyTextBox.Attributes.Add("runat", "server");
            MyTextBox.CausesValidation = false;
            MyTextBox.AutoPostBack = true;
            MyTextBox.TextChanged += new EventHandler(MyTextBox_TextChanged);
            picktexts.Controls.Add(MyTextBox);

        }

void MyTextBox_TextChanged(object sender, EventArgs e)
    {
        TextBox MyTextBox = sender as TextBox;
    }

しかし、テキストボックスを変更すると、textChanged が機能しません!!! どうしたの ?

HTML コード

<asp:UpdatePanel ID="UpdatePanel2" runat="server">
                <ContentTemplate>
                    <div id="picktexts" runat="server">
                    <asp:TextBox ID="txtAdress" runat="server" MaxLength="128" Width="250" />
                    <asp:RequiredFieldValidator ControlToValidate="txtAdress" Display="Dynamic" ID="rfvAddress" Text="* Required" runat="server" />
                    <asp:Button ID="bt_addtxtbox" runat="server" Text="Add more" OnClick="Add_TextBoxes"  CausesValidation="false" />
                    </div>
                    </ContentTemplate>
                    </asp:UpdatePanel>
4

1 に答える 1

0

I think the event handlers are getting lost between posts. the way ASP.NET works, every time you post a page back to itself, all objects are instantiated again, and their state is recovered from the ViewState. Normally a control that's declared in the aspx would reassociate itself with events by the declaration in its tag, which is not the case here.

So try associating the event handlers again during the page load. Like this:

void Page_Load (object sender, EventArgs e)
{
    foreach (Control c in picktexts.Controls)
    {
        ((TextBox)c).TextChanged += new EventHandler(MyTextBox_TextChanged);
    }
}

And see if it works.

于 2013-06-03T18:12:25.607 に答える