Reputation: 21
I am trying to update a simple query using web forms but to no avail. I have tried debugging the code but could not find where is the bug. There are two methods page_load()
and editProfile_click()
of which the code is following:
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["id"]);
string connetionString = null;
SqlConnection con;
SqlDataReader dr;
connetionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=AspNetInventory;Integrated Security=True";
con = new SqlConnection(connetionString);
try
{
con.Open();
string query = @"SELECT * FROM UserDetails WHERE employeeId = @id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Id", id);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Username.Text = dr[1].ToString();
UName.Text = dr[3].ToString();
UPhoneNo.Text = dr[4].ToString();
Uemail.Text = dr[5].ToString();
}
}//try
catch (SqlException ex)
{
Username.Text = "db Connection fail" + ex;
}
}
protected void SaveProfile_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["id"]);
string username, fullName, phoneNo, Email;
username = Convert.ToString(Username.Text);
fullName = Convert.ToString(UName.Text);
phoneNo = Convert.ToString(UPhoneNo.Text);
Email = Convert.ToString(Uemail.Text);
string connetionString = null;
SqlConnection con;
connetionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=AspNetInventory;Integrated Security=True";
con = new SqlConnection(connetionString);
try
{
con.Open();
string query = @"UPDATE UserDetails SET userName=@UserName, Name= @fullName, phoneNo = @Phone, Email=@uEmail WHERE employeeId='" + id + "'";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@UserName",username);
cmd.Parameters.AddWithValue("@fullName", fullName);
cmd.Parameters.AddWithValue("@Phone", phoneNo);
cmd.Parameters.AddWithValue("@uEmail", Email);
cmd.ExecuteNonQuery();
con.Close();
}//try
catch (SqlException ex)
{
Username.Text = "db Connection fail" + ex;
}
}
When I press the Update profile button the unchanged record from the data base gets fetched. Please tell me if there is a problem with the query.
Upvotes: 0
Views: 234
Reputation: 1
string query = @"UPDATE UserDetails SET userName=@UserName, Name= @fullName, phoneNo = @Phone, Email=@uEmail WHERE employeeId=" + id ;
Or :
string query = @"UPDATE UserDetails SET userName=@UserName, Name= @fullName, phoneNo = @Phone, Email=@uEmail WHERE employeeId=@ID";
cmd.Parameters.AddWithValue("@ID", id);
Upvotes: 0
Reputation: 39
Use if(!IsPostBack){ //here is your code } under page load because when you click on save button it first executes page_load then save click event. Otherwise page_load
overwrites your changes and saves.
Upvotes: 1