I have such a page
<form runat="server" id="NewForm">
Name: <asp:TextBox ID="Name" runat="server"></asp:TextBox>
<asp:Button ID="AddNewName" runat="server" Text="Add" OnClick="AddNewName_Click" />
<asp:Label ID="NewName" runat="server"></asp:Label>
</form>
In the code behind, I have a Page_Load which assign a value to the TextBox Name.
protected void Page_Load(object sender, EventArgs e)
{
Name.Text = "Enter Your Name Here";
}
Then upon the Click on the button AddNewName, I will write it in the Label NewName
protected void AddNewDivision_Click(object sender, EventArgs e)
{
NewName.Text = Name.Text;
}
But, no matter what I input in the Name TextBox, the Label only displays "Enter Your Name Here". It never updates to the actual content in the Name TextBox. What am I doing wrong with this code?
The problem is that you are always overwriting the changed value in Page_Load
. Instead, check the IsPostBack
property:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
Name.Text = "Enter Your Name Here";
}
You are re-assigning
the text to Name every time Page_Load
that over writes the text you entered in TextBox before reach AddNewDivision_Click
event. To assign it once on page load and do not over write the subsequent calls you can use Page.IsPostBack
property.
if(!Page.IsPostBack)
Name.Text = "Enter Your Name Here";
Or you can assign the text in design html and remove
the statement
from page_load
<asp:TextBox ID="Name" runat="server" Text="Enter Your Name Here"></asp:TextBox>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With