Reputation: 10590
I have a text box like this:
<asp:TextBox runat="server" ID="reasonNameTextBox"></asp:TextBox>
when I load the page in the first time, i put a value inside it like this:
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
Then, the user can enter his new value, and click save button.
when the user clicks save button, the value of the text box is still the value that I assigned when the page is loaded, not the value the the user has written. I tried to use Google Chrome F12 feature, and I found the error.
Please look at this image
as you see, the value that i wrote in the text box is New Value
, however, the value in the text box (when using F12) is still s
, where s
is the value that I assigned when the page is loaded.
why is that please?
Upvotes: 1
Views: 2386
Reputation: 6032
Changing the value doesn't update the DOM (unless you change it via javascript). So inspecting the textbox via developer tools, as you did, yields the text value you received from your server.
The interesting part lies in your WebPage's CodeBehind file. I assume it looks similar to this:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var results = GetResults();
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
}
In this case the textbox's value will be set every time, regardless of the user-input. What you have to do, is look for a postback:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var results = GetResults();
if (IsPostBack)
{
// retrieve the user input
var input = reasonNameTextBox.Text;
}
else
{
// set default value
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
}
}
Upvotes: 2
Reputation: 3216
The is because every time you are clicking on the button you are posting back and the page is again reloaded, Thus calling Page_Load, Which in turn is assigning the value you have assigned during page load.
To avoid this you need to do something like this :-
If(!IsPostback)
{
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
This, wouldn't update your textbox value with defaultvalue you have set during Page_Load and will take user updated value.
Upvotes: 3