سؤال

There is web site where user login. I navigate to user info page where the information are displayed by retrieving the info from db based on the username. username is unique. I display all info in text box like this:

SqlCommand cmd = new SqlCommand(query,con);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
txtFirstName.Text = sdr[0].ToString();
txtLastName.Text = sdr[1].ToString();
txtAge.Text = sdr[3].ToString();
txtUserName.Text = sdr[4].ToString();

Then when allow users to modify changes in the same text boxes and allow them to update.

string query = "UPDATE users SET FirstName=@firstName,LastName=@lastName,Age=@age,UserName=@userName WHERE UserName='"+userName+"'";

con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@firstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("@lastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@age", txtAge.Text);
cmd.Parameters.AddWithValue("@userName", txtUserName.Text);
cmd.ExecuteNonQuery();

But the value which the user changes are not being sent to db. I have done similar code before and it has worked. But now it fails to update. Where am I going wrong.

هل كانت مفيدة؟

المحلول

In the comments you say that this happens during Page_Load:

SqlCommand cmd = new SqlCommand(query,con);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
txtFirstName.Text = sdr[0].ToString();
txtLastName.Text = sdr[1].ToString();
txtAge.Text = sdr[3].ToString();
txtUserName.Text = sdr[4].ToString();

In the ASP.NET Page Lifecycle Page_Load gets called every time the page object instantiates, on every request. So even if you're clicking a button and not initially requesting the page, that button results in a request to that page on the server, so Page_Load runs before the click handler for the button on that request.

So what's happening is:

  • You request the page
  • Page_Load inserts the current values into the controls
  • You change the values on the page
  • You click a button
  • Page_Load inserts the current values into the controls
  • You update the database with the values in the controls

See the second-to-last line? Include a breakpoint in Page_Load when you debug this. You're overwriting the values before you save them.

You can fix this by wrapping your initialization code in a check to IsPostBack:

if (!IsPostBack)
{
    SqlCommand cmd = new SqlCommand(query,con);
    SqlDataReader sdr = cmd.ExecuteReader();
    sdr.Read();
    txtFirstName.Text = sdr[0].ToString();
    txtLastName.Text = sdr[1].ToString();
    txtAge.Text = sdr[3].ToString();
    txtUserName.Text = sdr[4].ToString();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top