ASP.NET:无法更新从数据库中读取的值
本文关键字:数据库 读取 更新 NET ASP | 更新日期: 2023-09-27 18:36:32
我想编辑从数据库中读取的值。我的读取代码是:(这在我的page_load中找到)
string uname = Session["ApplicantUsername1"].ToString();
txtUsername.Text = uname;
cs.Open();
SqlCommand cmd = new SqlCommand("SELECT NoALastName, NoAFirstName, NoAMiddleName FROM CustomerCreditReport WHERE ApplicantUsername = '" + uname + "'", cs);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
txtLname.Text = reader["NoALastName"].ToString();
txtFname.Text = reader["NoAFirstName"].ToString();
txtMname.Text = reader["NoAMiddleName"].ToString();
}
cs.Close();
reader.Close();
现在,这是我的保存/更新代码。(这是在Save_Click下)
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand("UPDATE CustomerCreditReport SET NoALastName = @NoALastName, NoAFirstName = @NoAFirstName, NoAMiddleName = @NoAMiddleName WHERE ApplicantUsername = '" + txtUsername.Text + "'", cs);
da.UpdateCommand.Parameters.Add("@NoALastName", SqlDbType.VarChar).Value = txtLname.Text;
da.UpdateCommand.Parameters.Add("@NoAFirstName", SqlDbType.VarChar).Value = txtFname.Text;
da.UpdateCommand.Parameters.Add("@NoAMiddleName", SqlDbType.VarChar).Value = txtMname.Text;
cs.Open();
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
我想知道我是否忽略了什么。请帮忙。谢谢。
在页面加载中,请确保将代码放在 if (!Page.IsPostBack)喜欢这个
if (!Page.IsPostBack)
{
string uname = Session["ApplicantUsername1"].ToString();
txtUsername.Text = uname;
cs.Open();
SqlCommand cmd = new SqlCommand("SELECT NoALastName, NoAFirstName, NoAMiddleName FROM CustomerCreditReport WHERE ApplicantUsername = '" + uname + "'", cs);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
txtLname.Text = reader["NoALastName"].ToString();
txtFname.Text = reader["NoAFirstName"].ToString();
txtMname.Text = reader["NoAMiddleName"].ToString();
}
cs.Close();
reader.Close();
}