使用CommandName从Gridview中删除行

时间:2014-11-26 18:46:59

标签: c# asp.net

我正在尝试使用Gridview从我的CommandName删除行,但它无效。我使用get RowIndex来执行此操作。

我没有收到任何错误,当我点击ImageButton时,它没有做任何事情。

这是我的代码:

<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>

这是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();
        }
    }
}

4 个答案:

答案 0 :(得分:0)

试试这个

而不是做你做的事情我建议你从DataBase中删除并再次绑定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();
       }
   }
 }

答案 1 :(得分:0)

试试这个:

<强> 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
    }

答案 2 :(得分:0)

如果您想要从数据库中删除该行并反映页面上的更改,请使用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();
        }

    }

如果您不记得ID的列索引,您仍可以ID follow this answer

的名称获取Grid Header

在你的页面加载

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();
     }
   }

编辑:网格不应该绑定PostBack,我建议不要这样做。不在Page_Load更新网格视图,而是将GridView包裹在UpdatePanel

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

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

                 </ContentTemplate>
          </asp:UpdatePanel>

然后在需要更新网格的地方调用UpdatePanel2.Update()(在这种情况下,您需要Bind要修改其源代码的网格RowCommand以及绑定调用{ {1}})

请记住,无论您做什么,都无法停止UpdatePanel2.Update(),因为按钮上有点击。

答案 3 :(得分:0)

我在运行时在Gridview中完成了行删除而没有数据表中的删除记录。请找到以下代码。

我的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>

在.cs文件中添加以下功能

protected void grdAddEditDefectParameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }

之后,以下代码删除行

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