我有一个网络表单不符合我的预期,我有点难过。在表单上,电话号码从数据库填充到文本框。这部分工作正常。然后,用户可以选择编辑文本框中的值,然后按下一个按钮,该按钮使用文本框中的值更新数据库中的值。这是不起作用的部分。
这是我的代码。
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class contact_edit : System.Web.UI.Page
{
//sql connection here
protected void Page_Load(object sender, EventArgs e)
{
string phoneNum = "";
cn.Open();
SqlCommand command = new SqlCommand("getContactInfo", cn);
command.CommandType = CommandType.StoredProcedure;
SqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read())
{
phoneNum = myReader.GetString(3).ToString();
}
cn.Close();
//If I take this part out and don't populate textbox,
//my update works. If I leave it, it does not
phone.Text = phoneNum.ToString();
}
protected void update_btn_Click(object sender, EventArgs e)
{
cn.Open();
phone.Text = "";
string updatedPhone = phone.Text;
string updateSQLString = "update contact set Phone_num = '" + updatedPhone +
"'";
SqlCommand updateCommand = new SqlCommand(updateSQLString, cn);
updateCommand.ExecuteNonQuery();
cn.Close();
Response.Redirect("contact_edit.aspx");
}
}
当我点击按钮调用我的更新方法时。它试图获得手机文本框的价值。但是在表单加载之后,我更改文本框值然后点击更新按钮,它会在表单加载时保持获取最初分配给文本框的值。为什么会这样?
答案 0 :(得分:0)
尝试将if (!Page.IsPostBack)
放在page_load代码
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string phoneNum = "";
cn.Open();
SqlCommand command = new SqlCommand("getContactInfo", cn);
command.CommandType = CommandType.StoredProcedure;
SqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read())
{
phoneNum = myReader.GetString(3).ToString();
}
cn.Close();
//If I take this part out and don't populate textbox,
//my update works. If I leave it, it does not
phone.Text = phoneNum.ToString();
}
}
答案 1 :(得分:0)
为什么会这样?
因为您在每次回发时都从数据库加载值。将其包裹在IsPostBack
中 - 检查:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// only load the value on the first load
}
}
答案 2 :(得分:0)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//access data here
//assign value here
phone.Text = phoneNum.ToString();
}
}