I got this code from a previous post on here about dynamically making a panel based ona click event of a button. For some reason its giving me two textbox’s and I’m having issues deciphering the code. Been a while since I’ve dealt with this kind of C#. It’s probably a simple fix, however like i said, been a while.
The ASP.net code is just a button so no need to paste it.
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; }
}
}
remove the Button1.Click line from your pageload.
if your your .aspx button already looks something like this:
then that means that when you click the button, your code is going to go through the Page_Load, which means it will execute your Eventhandler for Button1_Click, and after that it will go further down to your actual events, being Button1_Click again, so thats basically why you get 2 textboxes.