简体   繁体   中英

Delete Row From Gridview with CommandName

I am trying to delete Rows from my Gridview using a CommandName but its not working. I am using get RowIndex to do this.

I do not get any errors, it just doesn't do anything when I click on the ImageButton .

Here is my code:

<asp:GridView ID="GridView1" runat="server" Width="538px" BackColor="White"  BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" onselectedindexchanged="DropDownList5_SelectedIndexChanged" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" Font-Size="Small"  >
    <AlternatingRowStyle BackColor="White" />

    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="ImageButton1" runat="server" Height="16px" ImageUrl="~/images/delete.png" Width="16px" CommandName="DeleteRow" />
            </ItemTemplate>
            <HeaderStyle Width="30px" />
            <ItemStyle Height="10px" />
        </asp:TemplateField>
    </Columns>

    <FooterStyle BackColor="#CCCC99" />
    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
    <RowStyle BackColor="#F7F7DE" />
    <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FBFBF2" />
    <SortedAscendingHeaderStyle BackColor="#848384" />
    <SortedDescendingCellStyle BackColor="#EAEAD3" />
    <SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>

Here is cs code:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (Page.IsPostBack)
    {
        if (e.CommandName.Equals("DeleteRow"))
        {
            GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int RowIndex = oItem.RowIndex;
            GridView1.DeleteRow(RowIndex);
            DataBind();
        }
    }
}

try this

Instead of Doing what you did I will suggest you to Delete from DataBase and Again Bind the GridView

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{



    if (e.CommandName.Equals("DeleteRow"))
    {
        GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
        int RowIndex = oItem.RowIndex;

        girdivewBind(); // Bind your gridview again. 
    }

}


public void deleteRecord(string ID)
{
  using (SqlConnection con = new SqlConnection(cn.ConnectionString))
   {
     using (SqlCommand cmd = new SqlCommand())
     {
        cmd.CommandText = "delete from Mytable where ID=@id";
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@id", ID);
        con.Open();
        var temp = cmd.ExecuteNonQuery();
        con.Close();
       }
   }
 }

Try this:

GridView:

<ItemTemplate>
   <asp:ImageButton CommandName="DeleteProduct" ID="ImageButton1" runat="server" CausesValidation="false"    " ImageUrl="~/Admin/Images/SendToShop.png"/>
</ItemTemplate>

C#

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteProduct")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = grdCart.Rows[index];

            int productId = int.Parse(((Label)GridView1.Rows[row.RowIndex].FindControl("lbProdId")).Text);

            DeleteProduct(productId);
       }
    }

private void DeleteProduct (int productID)
    {
        //delete the product
    }

If you want to delete the row from database as well and reflect the changes on the page then use GridViewID_RowCommand

aspx

    <asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="DropDownList5_SelectedIndexChanged"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" >

        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:ImageButton ID="ImageButton1" runat="server"
     Height="16px" ImageUrl="~/images/delete.png"
    CommandName="DeleteRow" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

C#

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteRow")
        {
           int index = Convert.ToInt32(e.CommandArgument);
           GridViewRow selectedRow = GridView1.Rows[index];
           string id = selectedRow.Cells[0].Text; //assuming your ID is the first column of your grid
           SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString); //assuming your connection string is in web.config
           con.Open();
           SqlCommand sq = new SqlCommand("DELETE FROM myTable where id='" + id + "'", con);
           sq.ExecuteNonQuery();
           con.Close();
        }

    }

In case you do not remember the column index of your ID still you can get the ID value by the name of the Grid Header follow this answer

In your pageload

protected void Page_Load(object sender, EventArgs e)
    {
        if(this.IsPostBack)
       { 
        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
        con.Open();
        SqlCommand sqlCommand = new SqlCommand("SELECT * FROM myTable",con);
        SqlDataReader reader = sqlCommand.ExecuteReader();
        GridView1.DataSource = reader;
        GridView1.DataBind();
        con.Close();
     }
   }

EDIT: grids shouldn't be bind on PostBack , I recommend do not do this. Update the gridview not in Page_Load , instead wrap your GridView inside an UpdatePanel

<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
              <ContentTemplate>

  <asp:GridView ID="gv1" ...> ... </asp:GridView>

                 </ContentTemplate>
          </asp:UpdatePanel>

then call UpdatePanel2.Update() wherever you need to update your Grid (in this case you'll need to Bind the grid where you are modifying its source ie RowCommand and after binding call UpdatePanel2.Update() )

Remember whatever you do, you can not stop the PostBack because the click is on the button.

I have done row deliting in Gridview at runtime without delete record in datatable. Please find the code below.

My GridView

<asp:GridView ID="grdAddEditDefectParameterDetails" runat="server" OnRowDataBound="grdAddEditDefectParameterDetails_RowDataBound" OnRowDeleting="grdAddEditDefectParameterDetails_RowDeleting" >
<Columns>
    <asp:BoundField DataField="DEFECT_PARAM_CODE" HeaderStyle-CssClass="headTb4" Visible="false"
        HeaderText="Defect No.">
        <ItemStyle Wrap="False" />
    </asp:BoundField>
    <asp:TemplateField HeaderStyle-CssClass="headTb4" HeaderStyle-Width="5%" HeaderText="Select">
        <ItemTemplate>
            <asp:CheckBox ID="ChkStatus" runat="server" AutoPostBack="true" DataTextField="ACTIVE"
                onclick="javascript:return OnChange(this);" />
            <asp:HiddenField ID="idDefectParam" runat="server" Value='<%# Eval("DEFECT_PARAM_CODE") %>' />
        </ItemTemplate>
        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="5%" />
    </asp:TemplateField>
    <asp:BoundField DataField="DEFECT_PARAM_DESCRIPTION" ItemStyle-Width="44%" HeaderStyle-CssClass="headTb4"
        HeaderText="Defect Parameter Description" HtmlEncode="false">
        <ItemStyle Wrap="False" />
    </asp:BoundField>
    <asp:TemplateField HeaderText="Penalty Applicable" HeaderStyle-Width="7%" HeaderStyle-CssClass="headTb4">
        <ItemTemplate>
            <asp:CheckBox ID="ChkPenalty" Enabled="false" runat="server" DataTextField="PENALTY_APPLICABLE"></asp:CheckBox>
        </ItemTemplate>
        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="7%" />
    </asp:TemplateField>
    <asp:TemplateField HeaderStyle-CssClass="headTb4" HeaderText="Defect Weightage" HeaderStyle-Width="7%">
        <ItemTemplate>
            <asp:TextBox ID="txtAddDefectWeightage" runat="server" CssClass="inputSmallGrid"
                MaxLength="6" onkeypress="javascript:return isNumericKey(event);" Text="0.00"
                AutoCompleteType="Disabled"></asp:TextBox>
        </ItemTemplate>
        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="7%" />
    </asp:TemplateField>

</Columns>

In your .cs file add following function

protected void grdAddEditDefectParameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }

After that wright the following code to delete the row

grdAddEditDefectParameterDetails.DeleteRow(grdAddEditDefectParameterDetails.Rows[i].RowIndex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM