I have a problem which is bothering me for three days.
On my web form I want to have a button, on which click I want to make dynamicly five text boxes in asp:PlaceHolder.
And I want, that values which I enter in this texBoxes, are saved even after postBack. With second button i want to store them.
I’ve read articles about lifecycle of page, viewState, IsPostBack,… a lot of articles of dynamically created controls, but I’m still not able to program this.
There are several ways I tried, but without success. Below is the last version of my “masterpiece”. Please help me to crate this task, because it makes me sick. Thanks, Martin
namespace DynamicCreate
{
public partial class _Default : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox textBox;
private TextBox[] my_dynamicTextBoxes = new TextBox[5];
private string[] textBoxValues = new string[5];
protected void Page_Load(object sender, System.EventArgs e)
{
btn_save_tb_values.Click += new EventHandler(save_btnClick);
but_load_tb.Click += new EventHandler(creat_tb_btnClick);
int i = 0;
foreach (TextBox tb in my_dynamicTextBoxes)
{
if (ViewState["c_textBox" + i.ToString()] != null)
{
tb.Text = (string)ViewState["c_textBox" + i.ToString()];
i++;
}
else
{
textBox = new TextBox();
textBox.ID = "c_textBox" + i.ToString();
my_dynamicTextBoxes[i] = textBox;
i++;
}
}
}
protected void creat_tb_btnClick(object sender, EventArgs e)
{
int i = 0;
foreach (TextBox neww in my_dynamicTextBoxes)
{
c_placeholder.Controls.Add(neww);
c_placeholder.Controls.Add(new LiteralControl("<br>"));
ViewState["c_textBox" + i.ToString()] = neww.Text;
i++;
}
}
protected void save_btnClick(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++) {}
}
}
}
<form id="form1" runat="server">
<div>
<div> <asp:PlaceHolder ID="c_placeholder" runat="server"></asp:PlaceHolder> </div>
<div> <asp:Button runat="server" ID="but_load_tb" Text="Dodaj Polja!!"/> </div>
<div> <asp:Button runat="server" ID="btn_save_tb_values" Text="Izpisi Vrednosti!" /> </div
</div>
</form>
Here’s a simple example I came up with that will dynamically add 5 textboxes to a PlaceHolder when you click a “Create” button and will bring up the values when you click a “Save” button:
Default.aspx:
Default.aspx.cs: