-2

I want to delete the records from the Gridview on the click of ImageButton. Please see the GridView Code for your reference:-

<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="false" OnDataBound="grdCSRPageData_DataBound" PageSize="5" AllowPaging="true" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" OnRowCommand="grdCSRPageData_RowCommand">
                <AlternatingRowStyle BackColor="#CCCCCC" />
                <Columns>
                    <asp:TemplateField ItemStyle-Width="30">
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
                        <ItemTemplate>
                            <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
                            <span onclick="return confirm('Are you sure want to delete?')">
                                <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="DeleteRow" />
                            </span>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                            <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

Tried with 'RowCommand' property of GridView and stucked how to delete the Row See the code:-

 protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteRow")
        {
            //incase you need the row index 
            int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
            int Id = Convert.ToInt32(e.CommandArgument);
            //followed by your code 
        }
    }
Rahul Sutar
  • 260
  • 9
  • 36
  • 1
    Good luck! Seems like you're off to a good start. Do you actually have a question? – entropic Nov 24 '14 at 16:12
  • @entropic: I need code for update and delete on ImageButton – Rahul Sutar Nov 24 '14 at 16:13
  • ... and what have you tried so far that isn't working? – entropic Nov 24 '14 at 16:13
  • @entropic: I tried onRowCommand with CommandName property but it was not working. ' protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DeleteRow") { //incase you need the row index int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex; int Id = Convert.ToInt32(e.CommandArgument); //followed by your code } }' what to write in my code to delete from the table as well as the gridview – Rahul Sutar Nov 24 '14 at 16:15
  • 1. You should edit your question and put that code there. 2. What does "not working" mean? 3. I'll take a stab in the dark here - but you don't actually define a command name that you could reference on the `ImageButton` in your code above. – entropic Nov 24 '14 at 16:19

2 Answers2

0

try this

protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteRow")
        {
            int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
            grdCSRPageData.Rows.RemoveAt(rowIndex);
            //delete from database
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
               int Id = Convert.ToInt32(e.CommandArgument);
               string sql = "DELETE FROM YourTable WHERE ID = @ID";
               SqlCommand cmd = new SqlCommand(sql,connection);
               cmd.Parameters.AddWithValue("@ID",Id);
               cmd.ExecuteNonQuery();
           }
        }
    }

refer here for documentation about GridView remove.

SqlCommand documentation

update

to get the gridView from its row you can call this function

public static GridView GetParentGridView(GridViewRow row)
        {

            GridView gridView = (GridView)row.NamingContainer;
            return gridView;
        }

use it to get the gridview in my code

replace

 grdCSRPageData.Rows.RemoveAt(rowIndex)

with

GetParentGridView((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).Rows.RemoveAt(rowIndex)

be sure also to bind the grid only if there is no postback on page load

protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        //bind the gridView
      }
    }
faby
  • 7,394
  • 3
  • 27
  • 44
-1

Tried with Something like this and it worked.:-

<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="True" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" OnClientClick="return confirm('Are you sure you want to delete this record?')">
                <AlternatingRowStyle BackColor="#CCCCCC" />
                <Columns>
                    <%-- <asp:TemplateField ItemStyle-Width="30">
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>--%>
                    <asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
                        <ItemTemplate>
                            <%-- <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" />--%>
                            <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
                            <%-- <span onclick="return confirm('Are you sure want to delete?')"> -- %>
                                <%--<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" ></asp:LinkButton>--%>
                           <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                            <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

Also see the code behind:-

  protected void grdCSRPageData_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        bool IsDeleted = false;
        //getting key value, row id
        int Id = Convert.ToInt32(grdCSRPageData.DataKeys[e.RowIndex].Value.ToString());
        using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "DELETE FROM tbl_Pages WHERE Id=@ID";
                cmd.Parameters.AddWithValue("@ID", Id);
                cmd.Connection = conn;
                conn.Open();
                IsDeleted = cmd.ExecuteNonQuery() > 0;
                conn.Close();
            }
        }
        if (IsDeleted)
        {
            //record has been deleted successfully!
            //call here gridview bind method and replace it..
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrpage.aspx';", true); ;
            grdCSRPageData.DataBind();
        }
        else
        {
            //Error while deleting record
            Response.Write("Some error");
        }
    }

Also the binding of the data should be inside the '(!IsPostBack)' method

Rahul Sutar
  • 260
  • 9
  • 36
  • it seems to be very similar to my suggestion that I have wrote in chat. I don't understand why you have wrote the code as your answer ignoring my own answer – faby Nov 25 '14 at 14:11
  • faby, it doesn't mind.I got one thing, that I had to bind the data onPageLoad inside the(!IsPostBack). And that worked.. I will mark your answer, Not an Issue. Just posted if anyone wants to know in details – Rahul Sutar Nov 25 '14 at 14:15