Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current TextBox Text value in a button onClick event - asp.net

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?

like image 452
Jin Wang Avatar asked Dec 11 '12 17:12

Jin Wang


2 Answers

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";
}
like image 154
Tim Schmelter Avatar answered Nov 01 '22 23:11

Tim Schmelter


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>
like image 42
Adil Avatar answered Nov 01 '22 23:11

Adil