Reputation: 117
I got a question. When I put this code
protected void Page_Load(object sender, EventArgs e)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
**TextBox2.Text = email;
TextBox3.Text = UserId;**
}
My data will not be saved to the database.
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Membership SET Email = @email WHERE UserId = @id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@email", TextBox2.Text);
cmd.Parameters.AddWithValue("@id1", TextBox3.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
But when I removed
**TextBox2.Text = email;
TextBox3.Text = UserId;**
The data will be saved into database using above code. Can someone tell me why? Thanks in advance.
Upvotes: 3
Views: 677
Reputation: 51514
Given you never execute the command I can't explain it.
Add
cmd.ExecuteNonQuery();
To the end of your click method
Because you are setting the values in your page load event, they are overwriting the changed values in the controls when your button on postback. Wrap your page load code with a
if (!Page.IsPostback)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
TextBox2.Text = email;
TextBox3.Text = UserId;
}
Upvotes: 4
Reputation: 8838
Try the following
cmd.Connection = conn;
cmd.Connection.Open()
after you assign it and then
cmd.ExecuteNonQuery();
Upvotes: 0
Reputation: 85126
You are never executing your SQL so I'm very surprised that your DB is updating at all.
Take a look at the ExecuteNonQuery method. With your current query you are creating a SQLCommand and then never running the SQL.
Upvotes: 1