Please see the code below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="Div1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Create a TextBox" />
<asp:Button ID="Button2" runat="server" Text="Erase TextBox Text" />
</form>
</body>
</html>
..........................................
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Request.Params.ToString().IndexOf("Button1") > 0)
{
CreateTextBox();
}
else
{
if (Request.Params.ToString().IndexOf("Button2") > 0)
{
TextBox txtbx = CreateTextBox();
txtbx.Text = "";
}
}
}
}
TextBox CreateTextBox()
{
TextBox txtbx = new TextBox();
Div1.Controls.Add(txtbx);
return txtbx;
}
On PostBack, I check if ‘Button1’ or ‘Button2’ was pressed.
I press Button1 and a TextBox is dynamically created.
I enter some text in the TextBox and press Button1 again. The TextBox is recreated and the text I entered is preserved on PostBack.
When I press Button2, I want to recreate the TextBox, but I want to remove the text I previously entered. But even though I’ve specified txtbx.Text = “” the text is still preserved after PostBack.
How do I recreate the TextBox but remove the text entered?
(I want the text to be preserved if I push Button1, but not if I push Button2)
Thank you.
On the
page load, your context is not restored yet. If you want to override the state value of your control, handle theClickevent of each button and do the logic accordingly.