在此代码中,我使用URL传递 patientId 参数从数据库中读取患者信息。然后我在 Page_Load 中用5个文本框填充这些值。但是在 Update_Click ,代码无法访问更新的文本框值,它只读取文本框的初始值。我在调试时看到了它。在数据库级别没有问题。当我删除 Page_Load 代码并最初将文本框保留为空时, Update_Click 中的代码可以访问用户输入并更新值。有什么问题?
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
public partial class admin_Testadmin : System.Web.UI.Page
{
Patient patient = new Patient();
protected void Page_Load(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.select_patient, cn);
command.CommandType = CommandType.StoredProcedure;
int pid = int.Parse(Request.QueryString["patientId"]);
command.Parameters.AddWithValue("pid", pid);
command.Parameters["pid"].Direction = ParameterDirection.Input;
cn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = patient.Name = (String)reader[0];
txtSurname.Text = patient.Surname = (String)reader[1];
txtFathersname.Text = patient.Fathersname = (String)reader[2];
txtStatus.Text = patient.Status = (String)reader[3];
txtSuccessDescription.Text = patient.SuccessDescription = (String)reader[4];
patient.Id = (int)reader[5];
}
reader.Close();
cn.Close();
}
}
protected void Update_Click(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.update_patient, cn);
command.CommandType = CommandType.StoredProcedure;
patient.Name = txtName.Text.Trim();
patient.Surname = txtSurname.Text.Trim();
patient.Fathersname = txtFathersname.Text.Trim();
patient.Status = txtStatus.Text.Trim();
patient.SuccessDescription = txtSuccessDescription.Text;
patient.Id = int.Parse(Request.QueryString["patientId"]);
command.Parameters.Add("pname", MySqlDbType.VarChar).Value = patient.Name;
command.Parameters.Add("psurname", MySqlDbType.VarChar).Value = patient.Surname;
command.Parameters.Add("pfathersname", MySqlDbType.VarChar).Value = patient.Fathersname;
command.Parameters.Add("pstatus", MySqlDbType.VarChar).Value = patient.Status;
command.Parameters.Add("psuccessdescription", MySqlDbType.Text).Value = patient.SuccessDescription;
command.Parameters.AddWithValue("pid", patient.Id);
command.Parameters["pid"].Direction = ParameterDirection.Input;
cn.Open();
if (command.ExecuteNonQuery() > 0)
{
ResultLabel.Text = "";
ResultLabel.Text = "Update success";
}
cn.Close();
}
}
}
答案 0 :(得分:1)
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
// Rest of your code here
}
如果是回发,您不想覆盖用户键入的内容。
以下是有关ASP.NET page life cycle的一些文档。