Why does my save use the initial value of my TextBox and not the entered value?

I have a textbox on my website:

<asp:TextBox ID="Latitude" runat="server" ClientIDMode="Static" ></asp:TextBox>

On page load I fill that textbox with something from a databse:

protected void Page_Load(object sender, EventArgs e)
{
    Latitude.Text = thisPlace.Latitude;
}

When I want to update my databse with a new value in that textbox, it still updated the database with the one put in on page load:

protected void Save_Click(object sender, EventArgs e)
{
    setCoordinates(Latitude.Text);
}

How can I make sure that setCoordinates() retrieves the new value from the textbox and not the initial value from the database from Latitude.Text = thisPlace.Latitude;?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think its because PostBack

If you’re calling setCoordinates() on some button’s click event textbox’s new value will be lost. If that’s right change Page_Load like this one

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        Latitude.Text = thisPlace.Latitude;
    }    
}

Method 2

This is because the Page_Load event happens before your method setCoordinates is called. This mean that the Latitude.Text value is the same as before.

You should change the load function so it does not always set the initial value of the textbox.

By changing the page_load event with !Page.IsPostBack, the only time the initial value is given, is the first time the page originaly loads.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack) 
    {
        Latitude.Text = thisPlace.Latitude;
    }
}

Method 3

Page_Load executed each time page is loaded. Add IsPostBack check to reset text only on first page load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Latitude.Text = thisPlace.Latitude;
    }
}

Method 4

Check if the page is in postback otherwise the value will be replaced before the save

If(!IsPostBack){
    Latitude.Text = thisPlace.Latitude;
}

Method 5

You need to get the information from the request rather than using the property like that:

var theValue = this.Context.Request[this.myTextBox.ClientID];

Method 6

This happens if you load initial values all over again.

if (!IsPostBack)
{
    //call the function to load initial data into controls....
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x