Name:

Get current textbox value of TextBox in onClick event button - 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 Page_Load, which assign the value of the TextBox Name.

 protected void Page_Load(object sender, EventArgs e) { Name.Text = "Enter Your Name Here"; } 

Then, by clicking the AddNewName button, I will write it in Label NewName

 protected void AddNewDivision_Click(object sender, EventArgs e) { NewName.Text = Name.Text; } 

But no matter what I type in the Name text box, only "Enter Your Name Here" is displayed on the label. It never updates the actual contents in the Name text box. What am I doing wrong with this code?

+7
source share
3 answers

The problem is that you always overwrite 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"; } 
+16
source

You re-assigning text for the name each time Page_Load , which is above the text entry entered in the TextBox, until the AddNewDivision_Click event is AddNewDivision_Click . To assign it once at page loading and not to rewrite subsequent calls, you can use the Page.IsPostBack property.

  if(!Page.IsPostBack) Name.Text = "Enter Your Name Here"; 

Or you can assign text in html design and remove statement from Page_Load

 <asp:TextBox ID="Name" runat="server" Text="Enter Your Name Here"></asp:TextBox> 
+2
source

Another obvious problem:

 <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> 

Not the stars above. Then you wondered why this did not work:

 protected void **AddNewDivision_Click**(object sender, EventArgs e) { NewName.Text = Name.Text; } 

Again, note the stars. You did not name the correct void, in fact you probably called the void, which did not even exist.

0
source

All Articles