Gridview Edit_Update_Delete Manipulation
We are going to see how to Edit , Delete , update Gridview rows , when the Gridview is binded through Bound Column.
BoundField in Grid view and bind the data to each field using "Edit Column" option in smart tag of grid view.
We can also add images to Edit and Delete option in Grid view "edit columns" by adding a "commandfield".
This is the Code , here i have take some sample table to do this operation.
String con1 = ConfigurationManager.ConnectionStrings["con"].ToString();
DataSet ds = new DataSet();
To Edit Row
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindata();
}
To Update the Rows :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string i = GridView1.DataKeys[e.RowIndex].Value.ToString();
int j = Convert.ToInt32(i);
TextBox t1 = new TextBox();
t1 = (TextBox)GridView1.Rows[e.RowIndex].Cells [0].Controls [0];
TextBox t2 = new TextBox();
t2 = (TextBox)GridView1.Rows[e.RowIndex].Cells [1].Controls [0];
TextBox t3 = new TextBox();
t3 = (TextBox)GridView1.Rows[e.RowIndex].Cells [2].Controls [0];
SqlConnection con = new SqlConnection(con1);
string upt = "update Allergies set Allergy = @allergy, Symptoms = @symptom, Action_to_be_taken =@action where Allergy_id=" + j;
SqlCommand cmd = new SqlCommand(upt, con);
cmd.Parameters.Add("@allergy", SqlDbType.VarChar).Value = t1.Text;
cmd.Parameters.Add("@symptom", SqlDbType.VarChar).Value = t2.Text;
cmd.Parameters.Add("@action", SqlDbType.VarChar).Value = t3.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bindata();
}
To Cancel the Edit rows :
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindata();
}
To Delete the Rows :
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string i = GridView1.DataKeys[e.RowIndex].Value.ToString();
int j = Convert.ToInt32(i);
SqlConnection con = new SqlConnection(con1);
string del = "Delete from Allergies where Allergy_id=" + j;
SqlCommand cmd = new SqlCommand(del, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bindata();
}