问题
I've a following requirement for my asp.net page:
User can add a textbox dynamically on a page A by clicking on link "Add a new category" hyperlink
He clicks submit button on page A and gets redirected to page B.
When he clicks on page A link from this page, the textboxes that he added should be persisted.
Can someone help me with the code on this?
Appreciate your help!
回答1:
In the ButtonClick Method write.
TextBox tb = new TextBox();
Parent.Controls.Add( tb );
The Parent is the control you want to add the textbox to, for instance a panel.
You can also look at this resource.
Hope it helps.
回答2:
Adding a user control dynamically is simple. But in this case, I don't think you need to do that, instead you should look at creating a repeater with a textbox inside it, and when the user clicks Add Category, add one item to the repeater datasource.
This way you can handle both control creation and state persistence at the same time.
回答3:
Dynamically creating Textboxes:
suppose you have page like this
when you enter '1' in textbox and click on ADD button,output will be like display one textbox below.. i have designed like this,
i have one textbox and placeholder for displaying dynamic textboxes.. double click on Add button...in btnadd_click,you have to write the following code
protected void btnadd_Click(object sender, EventArgs e) {
int i;
for (i = 0; i < Convert.ToInt32(txtno.Text); i++)
{
TextBox txtbox = new TextBox();
phtxt.Controls.Add(txtbox);
phtxt.Controls.Add(new LiteralControl("<br>"));
}
}
debug it... and the output is,
回答4:
As others have stated adding the text box dynamically is fairly straight forward, just create the Textbox and add it to the controls collections wherever you need it to show up. You then need to store the information that this user gets this additional text box. Assuming that this is meant for long term, you will need to store this information in your backend store. Whenever you are constructing the page you will need to read the store information first to see what textboxes to create.
I would suggest doing it as follows. In the Onload event, if you have not done so before, load the dynamic information from your DB. Add any necessary controls to the page and store this information in viewstate. On any subsequent postbacks, read the information from viewstate to add the additional controls. This will save you from having to read constantly from the database on each postback.
回答5:
dealing with dynamic user controls can be a pain in the ass.
as a rule of thumb i follow, whenever you create a dynamic user control, then you must set it's ID so ASP.net can reallocate it on post back, and to keep the controls values after post back you should reload your user controls on Page_Init event.
hope this helps.
来源:https://stackoverflow.com/questions/737981/how-do-i-add-a-textbox-dynamically-in-asp-net