Kajin

Kajin

  • NA
  • 9
  • 12.9k

Not able to update using SqlCommand. Please help. Urgent..!!

Jun 22 2011 12:14 PM
I m  using SqlDataAdapter to fetch data from database and display the data in textboxes. After that i want to edit the data in the textboxes itself and save back the changed data to the same database. For that i m using SqlCommand. But its taking the already fetched data only, and updating it to the database, hence showing no change to the data.

Below are some sample code:

SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd;
SqlDataAdapter sda;
int counterid;

protected void Page_Load(object sender, EventArgs e)
{
        conn.Open();
            counterid = Convert.ToInt32(Session["counter"].ToString()); //taking counterid from session which was made in previous page.

            sda = new SqlDataAdapter("select * from Counters where CounterID=@counterid", conn);
            sda.SelectCommand.Parameters.Add("@counterid", SqlDbType.Int).Value = counterid;
            DataTable dt = new DataTable();
            sda.Fill(dt);

            lblCounterId.Text = dt.Rows[0]["CounterID"].ToString();
            txtCounterName.Text = dt.Rows[0]["CounterName"].ToString();
            conn.Close();
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
        conn.Open();
        cmd = new SqlCommand("update Counters set CounterName=@countername where CounterID=@counterid", conn);
        cmd.Parameters.Add("@counterid", SqlDbType.Int).Value = counterid;
        cmd.Parameters.Add("@countername", SqlDbType.VarChar).Value = txtCounterName.Text;
        cmd.ExecuteNonQuery();      
        conn.Close();
        Response.Redirect("ManageCounterSearch.aspx");
        Session["counter"] = null;
        counterid = 0;
}

Answers (10)