Sending two text fields as opposed to one dynamically

I got this code from a previous post here about dynamically creating a panel based on a button click event. For some reason, it gives me two text fields, and I am having problems decrypting the code. It has been some time since I dealt with this kind of C #. This is probably a simple fix, but as I said, some time has passed. ASP.net code is just a button, so there is no need to embed it.

WITH#:

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; } } } 
+4
source share
2 answers

remove the line Button1.Click from your pageload.

  Button1.Click += new EventHandler(Button1_Click); 

if your .aspx button already looks something like this:

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

this means that when you click the button, your code will go through Page_Load, which means that it will execute your Eventhandler for Button1_Click, and after that it will go further to your actual events by clicking Button1_Click again, so basically why you get 2 text fields.

+2
source

Does your button have an event bound to it already on the asp page?

 Button1.Click += new EventHandler(Button1_Click); 

It seems that this may give you some problems, especially when rebooting.

+2
source

Source: https://habr.com/ru/post/1435340/


All Articles