Unable to update record in textbox in C#

86 views Asked by At

I am trying to do edit inside grid view. When I click edit button to update record in text box it shows previous record. Please check. I think the error is in Row updating event.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        fill_grd1();
    }
}

public void fill_grd1()
{
    con.Open();
    SqlCommand cmd = new SqlCommand("usp_country_get", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows.Count > 0)
    {
        grd1.DataSource = ds;
        grd1.DataBind();
    }
    else
    {
        grd1.DataSource = null;
        grd1.DataBind();
    }
    con.Close();
}

protected void savebtn_Click(object sender, EventArgs e)
{
    con.Open();
    SqlCommand cmd = new SqlCommand("usp_country_insert", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@cname", txtcname.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    fill_grd1();
}

protected void grd1_RowEditing(object sender, GridViewEditEventArgs e)
{
    grd1.EditIndex = e.NewEditIndex;
    fill_grd1();
}

protected void grd1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int id = int.Parse(grd1.DataKeys[e.RowIndex].Value.ToString());
    con.Open();
    SqlCommand cmd = new SqlCommand("usp_country_delete", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@cid", id);
    cmd.ExecuteNonQuery();

    con.Close();
    fill_grd1();
}

protected void grd1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    TextBox TB1 = (TextBox)grd1.Rows[e.RowIndex].FindControl("edittxtcname");

    int id = int.Parse(grd1.DataKeys[e.RowIndex].Value.ToString());
    con.Open();
    SqlCommand cmd = new SqlCommand("usp_country_update", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@cid", id);
    cmd.Parameters.AddWithValue("@cname", TB1.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    grd1.EditIndex = -1;
    fill_grd1();
}

protected void grd1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    grd1.EditIndex = -1;
    fill_grd1();
}

protected void grd1_RowDataBound(object sender, GridViewRowEventArgs e)
{

}

protected void grd1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    con.Open();
    SqlCommand cmd = new SqlCommand("usp_country_status_change", con);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue("@cid", e.CommandArgument);

    cmd.ExecuteNonQuery();

    con.Close();

    fill_grd1();
}
0

There are 0 answers