Reputation: 499
I want to generate dynamically textbox in asp.net and c#. This code works only once, but I want any time click the button, two textboxes added.
private void CreateTextBox(string ID)
{
TextBox txt = new TextBox();
txt.ID = ID;
txt.Width = Unit.Pixel(150);
txt.AutoPostBack = false;
TextBox txt2 = new TextBox();
txt2.ID = ID + "s";
txt2.Width = Unit.Pixel(100);
txt2.AutoPostBack = false;
Panel1.Controls.Add(txt);
Panel1.Controls.Add(new LiteralControl("  "));
Panel1.Controls.Add(txt2);
Panel1.Controls.Add(new LiteralControl("<br>"));
}
protected void Button2_Click(object sender, EventArgs e)
{
CreateTextBox("txtTag-" + index.ToString());
index ++;
}
index is global static int variable.
What is the problem?
Upvotes: 0
Views: 446
Reputation: 46
you can use ControlRenderer instead of this, such as this:
protected void btn_Click(object sender, EventArgs e)
{
TextBox textName;
textName = new TextBox();
textName.TextChanged += new EventHandler(textName_TextChanged);
string divContect = ControlRenderer(divTextBox);
divTextBox.InnerHtml = divContect + ControlRenderer(textName);
}
protected void textName_TextChanged(object sender, EventArgs e)
{
}
public string ControlRenderer(Control control)
{
StringWriter writer = new StringWriter();
control.RenderControl(new HtmlTextWriter(writer));
return writer.ToString();
}
Upvotes: 1
Reputation: 301
You can add controls pragmatically only during the page's initialization stage, see ASP.NET Page Life Cycle Overview
Upvotes: 0
Reputation: 302
Use this code
int index = 1;
while(index <=2)
{
CreateTextBox("txtTag-" + index.ToString());
index++;
}
Upvotes: 0
Reputation: 939
U need to learn the Page Life Cycle of asp.net. Http is a stateless protocol The server does not remember anything about the previous requests
Y don't u Learn about using Session
and then keep track of the index in the Session
variable
Upvotes: 1