TextBox的文本在后面的代码中不会改变

所以我的网站上有一个文本框:

 

并在页面加载时我用数据库中的东西填充该文本框:

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

但是当我想在该文本框中使用新值更新我的数据库时,它仍然使用放在页面加载中的数据库更新数据库:

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

这是正常的吗? 如何确保我在setCoordinates()中从文本框中获取新值,而不是使用Latitude.Text = thisPlace.Latitude从文本框中获取的值; ?

我认为这是因为PostBack

如果您在某个按钮的单击事件文本框上调用setCoordinates() ,则新值将丢失。 如果这是正确的改变Page_Load像这样

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

这是因为Page_Load事件在调用方法setCoordinates之前发生。 这意味着Latitude.Text值与之前相同。

您应该更改加载函数,以便它不总是设置文本框的初始值。

通过使用!Page.IsPostBack更改page_load事件,给出初始值的唯一时间是页面首次加载时。

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

每次加载页面时都会执行Page_Load 。 添加IsPostBack检查以仅在第一页加载时重置文本:

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

检查页面是否在回发中,否则在保存之前将替换该值

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

您需要从请求中获取信息,而不是使用以下属性:

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

如果再次加载初始值,则会发生这种情况。

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