编程语言
首页 > 编程语言> > c# – 发送两个文本框而不是动态文本框

c# – 发送两个文本框而不是动态文本框

作者:互联网

我从上一篇文章中得到了这个代码,关于动态制作一个基于按钮点击事件的面板.由于某种原因,它给了我两个文本框,我有解密代码的问题.我已经处理过这种C#了一段时间.这可能是一个简单的修复,但就像我说的那样,已经有一段时间了.
ASP.net代码只是一个按钮,因此无需粘贴它.

C#:

public partial class Testing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    // Add any controls that have been previously added dynamically
    for (int i = 0; i < TotalNumberAdded; ++i)
    {
        AddControls(i + 1);
    }

    // Attach the event handler to the button
    Button1.Click += new EventHandler(Button1_Click);


}

protected void Button1_Click(object sender, EventArgs e)
{
    // Increase the number added and add the new label and textbox
    TotalNumberAdded++;
    AddControls(TotalNumberAdded);

}
private void AddControls(int controlNumber)
    {
        var newPanel = new Panel();
        var newLabel = new Label();
        var newTextbox = new TextBox();

        // textbox needs a unique id to maintain state information
        newTextbox.ID = "TextBox_" + controlNumber;

        newLabel.Text = "Nature Of Accident";

        // add the label and textbox to the panel, then add the panel to the form
        newPanel.Controls.Add(newLabel);
        newPanel.Controls.Add(newTextbox);
        form1.Controls.Add(newPanel);
    }

    protected int TotalNumberAdded
    {
        get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
        set { ViewState["TotalNumberAdded"] = value; }
    }



}

解决方法:

从页面加载中删除Button1.Click行.

 Button1.Click += new EventHandler(Button1_Click);

如果您的.aspx按钮看起来像这样:

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

然后这意味着当你点击按钮时,你的代码将通过Page_Load,这意味着它将为Button1_Click执行你的Eventhandler,然后它将进一步下降到你的实际事件,再次是Button1_Click,所以这基本上是为什么你得到2个文本框.

标签:c,dynamic,asp-net,buttonclick
来源: https://codeday.me/bug/20190625/1288418.html