Aligator3000
Aligator3000

Reputation: 345

Database Update

I am using the follwing code to update a person's email and password in the db. I have a datagridview which has only one row. When I hit the Update button, nothing happens - the page is refreshed and the values in the textboxes go back to what they were before....the update is not working. Please help. Thanks!

protected void btnUpdateAccount_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(GetConnectionString());

    string sql = "UPDATE Member SET [Email] = @email, [Password] = @password WHERE [MemberID] = '" + mem_id + "'";

    TextBox email = email = (TextBox)Gridview1.Rows[0].FindControl("user_email");
    TextBox password = (TextBox)Gridview1.Rows[0].FindControl("user_password");

    try
    {

        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);

        cmd.Parameters.Add("@email", SqlDbType.VarChar);
        cmd.Parameters.Add("@password", SqlDbType.VarChar);

        cmd.Parameters["@email"].Value = email.Text;
        cmd.Parameters["@password"].Value = password.Text;

        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();

    }
    catch (System.Data.SqlClient.SqlException ex)
    {

        string msg = "Insert Error: ";
        msg += ex.Message;
        throw new Exception(msg);
    }

    finally
    {
        conn.Close();
    }

}

Upvotes: 0

Views: 264

Answers (4)

Robbie Tapping
Robbie Tapping

Reputation: 2556

Make sure to put in your PageLoad Clause

** Change Made ** As per @marc_s comment changed if(this.IsPostBack == true) to if(this.IsPostBack) this.IsPostBack is boolean.


if(this.IsPostBack)
{
//dont load page
}

Upvotes: 0

Jemes
Jemes

Reputation: 2842

There are a number of things that could be happening.

  1. 1) The btnUpdateAccount_Click event is never raised. To fix this, make sure the asp:Button tag has an OnClick="btnUpdateAccount_Click" attribute set.
  2. An exception is being thrown and that you're not noticing.
  3. The database is being updated, but you did not load/bind the data again to display the updated values.

Upvotes: 0

safi
safi

Reputation: 3766

cmd.ExecuteNonQuery(); it return an integer value, so you can put. int i = cmd.ExecuteNonQuery(); and see what it is returning, also you can use finally after catch to make sure the db con is closed. here you are just using it in the catch, also try to put break point and see if the parameter are passed in correct way and follow it till the end. like

finally
        {
            if (con != null)
            {
                con.Close();
            }
        }

Upvotes: 1

Smarthinker
Smarthinker

Reputation: 1

You need to bind the data from database again to get the new changes. grid view .bind()

Upvotes: 0

Related Questions