Akhter HUssain

Akhter HUssain

  • 720
  • 1.3k
  • 102.3k

Row delete from database or Viewstate/Datatable

Jun 4 2020 1:59 PM
i have gridview,i want condition to delete row from gridview,
  1. <asp:GridView ID="GridView1" runat="server" AllowSorting="True" HorizontalAlign="Center" AutoGenerateColumns="false" CssClass="mygrdContent" HeaderStyle-BackColor="#66ccff" HeaderStyle-CssClass="header" HeaderStyle-ForeColor="White" OnRowDataBound="GridView1_RowDataBound" OnRowDeleting="GridView1_RowDeleting" PagerStyle-CssClass="pager" RowStyle-CssClass="rows" Width="452px" ShowFooter="True">  
  2. <Columns>  
  3. <asp:TemplateField HeaderText="ID">  
  4. <ItemTemplate>  
  5. <asp:Label ID="D_CID" runat="server" Text='<%#Bind("D_CID")%>'></asp:Label>  
  6. </ItemTemplate>  
  7. </asp:TemplateField>  
  8. <asp:TemplateField HeaderText="Container">  
  9. <ItemTemplate>  
  10. <asp:Label ID="Contnam" runat="server" Text='<%#Bind("Contnam")%>'></asp:Label>  
  11. </ItemTemplate>  
  12. </asp:TemplateField>  
  13. <asp:TemplateField HeaderText="QTY">  
  14. <ItemTemplate>  
  15. <asp:Label ID="QTY" runat="server" Text='<%#Bind("QTY")%>'></asp:Label>  
  16. </ItemTemplate>  
  17. <FooterTemplate>  
  18. <asp:Label ID="lblTotal1" runat="server"></asp:Label>  
  19. </FooterTemplate>  
  20. </asp:TemplateField>  
  21. <asp:TemplateField>  
  22. <ItemTemplate>  
  23. </ItemTemplate>  
  24. <EditItemTemplate>  
  25. </EditItemTemplate>  
  26. </asp:TemplateField>  
  27. <asp:CommandField ButtonType="Button" ShowDeleteButton="True" />  
  28. </Columns>  
  29. <HeaderStyle BackColor="#66CCFF" ForeColor="White" />  
  30. <SelectedRowStyle BackColor="Yellow" />  
  31. </asp:GridView>  
if i have data in gridview in datatable/Viewstate then it delete from viewstate if first column id does not exit ,
if i have ID in first column ,which i retrieved from database then it deleted from database below i tried but it is not working
  1. protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  2. {  
  3. int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);  
  4. int index = Convert.ToInt32(e.RowIndex);  
  5. DataTable dt = (DataTable)ViewState["dt"];  
  6. // Delete from ViewState.  
  7. dt.Rows[index].Delete();  
  8. ViewState["dt"] = dt;  
  9. string query = "delete from tbl_Import_Detail WHERE D_CID = @Id";  
  10. using (SqlCommand cmd = new SqlCommand(query))  
  11. {  
  12. cmd.Connection = con;  
  13. cmd.Parameters.AddWithValue("@Id", id);  
  14. con.Open();  
  15. cmd.ExecuteNonQuery();  
  16. con.Close();  
  17. }  
  18. BindGridView();  

Answers (5)