简体   繁体   English

使用 CommandName 从 Gridview 中删除行

[英]Delete Row From Gridview with CommandName

I am trying to delete Rows from my Gridview using a CommandName but its not working.我正在尝试使用CommandName从我的Gridview删除行,但它不起作用。 I am using get RowIndex to do this.我正在使用 get RowIndex来做到这一点。

I do not get any errors, it just doesn't do anything when I click on the ImageButton .我没有收到任何错误,当我单击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:这是cs代码:

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而不是做你所做的,我会建议你从数据库中删除并再次绑定 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# 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如果您还想从数据库中删除该行并在页面上反映更改,请使用GridViewID_RowCommand

aspx 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# 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如果您不记得ID的列索引,您仍然可以通过Grid Header的名称获取ID值,请遵循此答案

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.编辑:网格不应该绑定在PostBack ,我建议不要这样做。 Update the gridview not in Page_Load , instead wrap your GridView inside an UpdatePanel更新不在Page_Load的 gridview ,而是将GridView包装在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() )然后在您需要更新网格的任何地方调用UpdatePanel2.Update() (在这种情况下,您需要在修改其源的地方Bind网格,即RowCommand并在绑定之后调用UpdatePanel2.Update()

Remember whatever you do, you can not stop the PostBack because the click is on the button.请记住,无论您做什么,都无法停止PostBack因为单击是在按钮上。

I have done row deliting in Gridview at runtime without delete record in datatable.我在运行时在 Gridview 中完成了行删除,而没有删除数据表中的记录。 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在您的 .cs 文件中添加以下功能

protected void grdAddEditDefectParameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }

After that wright the following code to delete the row之后,使用以下代码删除该行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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