I have a form that is supposed to have defalt values, which the user can decide to change in some fields. The inputs are set up like this:
<input type="text" id="username" clientidmode="static" runat="server" />
I am setting the default data at the start of Page_Load() like this:
username.Value = "test"
And I'm getting the values later in if(isPostBack) like this:
string sUsername = username.Value;
The idea is that they will be able to change certain values about the user, or just leave the default values if they don't want to change that field.
The issue is that when I'm getting the field values in if(isPostBack) I'm just getting the values I've set at the start of Page_Load() even if the user changed the form values.
What am I doing wrong?
Here is a simple way to reproduce this. Create an asp.net project and add a WebForm.
Then add this to the page:
<input type="text" id="username" runat="server" />
<input type="submit" />
and add this to the code behind:
protected void Page_Load(object sender, EventArgs e)
{
username.Value = "Test";
if (IsPostBack)
{
string sUsername = username.Value;
}
}
CodePudding user response:
Your variable declaration should be inside !IsPostBack
if(!IsPostBack)
{
username.Value = "test"
}
CodePudding user response:
The issue is that as soon as you click on something else, your page load event triggers and your page loads first then your button click event occurs.
You have put the !IsPostBack at the wrong place. You need to keep the default data at the start of Page_Load() inside !IsPostBack(), then get the values later anywhere you want, inside any button_click event.
Have a look at this page: Edit Textbox not working (It is not taking the new data inserted and submitted)
Although, if you could have given some better view of code it would have been easy to tell.