我正在尝试更新sql server中的表但它无法正常工作。这是我的代码
SqlConnection conn;
string connString = ConfigurationManager.ConnectionStrings["Alumnidb"].ConnectionString;
string userName;
SqlCommand cmdProfile, cmdUpdate;
SqlDataReader reader;
string UserId;
protected void Page_Load(object sender, EventArgs e)
{
userName = Request.QueryString["UserName"].ToString();
RetriveProfile();
}
protected void RetriveProfile()
{
conn = new SqlConnection(connString);
cmdProfile = new SqlCommand("SELECT Name, UserId FROM UserProfile WHERE UserName=@UserName",conn);
cmdProfile.Parameters.AddWithValue("@UserName",userName);
conn.Open();
reader = cmdProfile.ExecuteReader();
while (reader.Read())
{
TextBoxName.Text = reader["Name"].ToString();
UserId = reader["UserId"].ToString();
}
conn.Close();
}
protected void buttonUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connString);
cmdUpdate = new SqlCommand("UPDATE UserProfile SET Name=@Name WHERE UserId=@UserId",conn);
cmdUpdate.Parameters.AddWithValue("@UserId",UserId);
cmdUpdate.Parameters.AddWithValue("@Name",TextBoxName.Text.ToString());
conn.Open();
cmdUpdate.ExecuteScalar();
conn.Close();
}
和.aspx文件
Name: <asp:TextBox ID="TextBoxName" runat="server" ></asp:TextBox>
<asp:Button ID="buttonUpdate" runat="server" Text="UpDate"
onclick="buttonUpdate_Click"/>
它显示我之前更新的值。 。我检查了sql server,那里也没有变化 我究竟做错了什么? 我们将不胜感激。 。 .Thanx
答案 0 :(得分:1)
问题是,即使您处于回发状态,也会填充Page_Load
中的所有值。因此,如果用户点击更新按钮Page_Load
首先被触发,则从数据库加载所有值,并将TextBox.Text
值设置为旧值。所以所有的变化都会丢失。
因此请使用IsPostBack
属性:
protected void Page_Load(object sender, EventArgs e)
{
userName = Request.QueryString["UserName"].ToString();
if(!IsPostBack)
RetriveProfile();
}
由于您从sql查询中获取UserID
,并且您需要在更新中有多个选项。您可以在回发中保留用户ID,例如在ViewState
或Session
中。这可以在RetriveProfile
。
protected void RetriveProfile()
{
conn = new SqlConnection(connString);
cmdProfile = new SqlCommand("SELECT Name, UserId FROM UserProfile WHERE UserName=@UserName",conn);
cmdProfile.Parameters.AddWithValue("@UserName",userName);
conn.Open();
reader = cmdProfile.ExecuteReader();
while (reader.Read())
{
TextBoxName.Text = reader["Name"].ToString();
UserId = reader["UserId"].ToString();
}
conn.Close();
}
将字段UserID
更改为属性:
private string UserId {
get { return (string)ViewState["UserID"]; }
set { ViewState["UserID"] = value;}
}
请注意,由于HTTP的无状态,所有变量都放在每个页面生命周期的末尾。因此,你需要在某个地方坚持下去。
Nine options for managing persistent User State in your ASP.NET Application