i am new to asp.net. i am trying to do a simple application of adding,inserting and deleting rows in gridview. i am using C#.net and javascript.
My edit/update works but i have problems in deleting the rows in the datagrid. i have used command fields(properties-columns) edit,update,cancel and delete commands. i changed it to template field. both are as buttons. ihave changed the id of Delete command to btDelete.
The following is the code for edit and update THIS CODE WORKS
Expand|Select|Wrap|Line Numbers
- protected void GridView2_RowUpdating(object sender,GridViewUpdateEventArgs e)
- {
- String S1;SqlConnection MyCon = new SqlConnection("Server=HEMA\\SQLEXPRESS;Integrated Security=SSPI;database=demo");
- MyCon.Open();
- Button b1 = new Button();
- TextBox t1 = new TextBox();
- TextBox t2 = new TextBox();
- foreach (GridViewRow gv in GridView2.Rows)
- {
- b1 = (Button)gv.FindControl("button1");
- t2 = (TextBox)gv.FindControl("TextBox2");
- t1 = (TextBox)gv.FindControl("TextBox1");if (b1.CommandName == "Update")
- {
- S1 = "update t1 set name='" + t2.Text + "' where id=" + t1.Text + "";
- SqlCommand UpdateCmd = new SqlCommand(S1, MyCon);
- Response.Write("updated");
- UpdateCmd.ExecuteNonQuery();
- }
- }
- MyCon.Close();
- }
Expand|Select|Wrap|Line Numbers
- protected void GridView2_RowEditing(Object sender, GridViewEditEventArgs e)
- {
- GridView2.EditIndex = e.NewEditIndex;
- Display();
- }
- public void Display()
- {
- SqlConnection GridCon = new SqlConnection("Server=HEMA\\SQLEXPRESS;Integrated Security=SSPI;database=demo");
- GridCon.Open();
- SqlDataAdapter MyDa = new SqlDataAdapter("select ID,name,date,qty,price,amount from t1", GridCon);
- DataSet MyDs = new DataSet();
- DataTable MyDt = new DataTable();
- MyDa.Fill(MyDt);
- GridView2.DataSource = MyDt;
- GridView2.DataBind();
- }
This is the code for delete WHICH DOES NOT WORK
Expand|Select|Wrap|Line Numbers
- protected void GridView2_RowDeleting(object sender,GridViewDeleteEventArgs e)
- {
- String S1;SqlConnection MyCon = new SqlConnection("Server=HEMA\\SQLEXPRESS;Integrated Security=SSPI;database=demo");
- MyCon.Open();
- Button b1 = new Button();
- foreach (GridViewRow gd in GridView2.Rows)
- {
- b1 = (Button)gd.FindControl("btDelete");
- if (b1.CommandName=="Delete")
- {
- S1 = "delete from demo where id=" + gd.Cells[0].Text;
- SqlCommand DeleteCmd = new SqlCommand(S1, MyCon);
- DeleteCmd.ExecuteNonQuery();
- Response.Write("deleted");
- }
- }
- }
This is the code on asp side
Expand|Select|Wrap|Line Numbers
- <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" Style="z-index: 104;
- left: 66px; position: absolute; top: 405px" Width="581px" OnRowEditing="GridView2_RowEditing"
- OnRowDeleting="GridView2_RowDeleting" OnRowUpdating="GridView2_RowUpdating"
- OnSelectedIndexChanged="GridView2_SelectedIndexChanged">
ANY HELP PLEASE