通过LinkBut​​ton从asp gridview中删除行

时间:2012-09-21 13:46:36

标签: c# gridview

我花了很长时间研究如何做到这一点,但没有运气。

<asp:GridView runat="server" ID="TBDSPCGrid"
                    AutoGenerateColumns="false"
                    AllowPaging="true"
                    AllowSorting="false"
                    DataKeyNames="SPID,CategoryId,Category,RowNum, PurchaseDate, Title, Description,SFItemId" 
                    OnRowDataBound="TBDSPC_RowDataBound"
                    OnRowCreated="TBDSPC_RowCreated"
                    OnRowCommand="TBDSPC_Command"
                    OnPageIndexChanging="TBDSPC_PageIndexChanging"
                    OnRowDeleting="TBDSPC_OnRowDeleting">
                    <Columns>
                        <asp:TemplateField HeaderText="Timeouts" ItemStyle-Width="40px" ItemStyle-Wrap="false"
                            ItemStyle-CssClass="padding-right">
                            <ItemTemplate>
                                <div class="targeted-icons">
                                    <asp:LinkButton runat="server" id="LinkButton1" CommandName="delete" CommandArgument='<%#Eval("SFItemId")%>'
                                    ><img src="delete.png" /></asp:LinkButton>
                                </div>
                            </ItemTemplate>
                        </asp:TemplateField>

那我该怎么办?

protected void TBDSPCGrid_OnRowDeleting(object     sender, GridViewDeleteEventArgs e)
    {
        // do something
    }

我尝试了这个但它没有用...它给了我一个错误“对象引用未设置为对象的实例”

protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
    {
        GridView gv = (GridView)sender;
        switch (e.CommandName)
        {
            case "delete":
                {
                    DataTable test = TargetedSpView.ToTable();
                    test.Rows[0].Delete();
                    test.AcceptChanges();
                    TargetedSpView = test.DefaultView;
                    this.TBDSPCGrid.DataSource = this.TargetedSpView;
                    this.TBDSPCGrid.DataBind();
                }
                break;
}
}

1 个答案:

答案 0 :(得分:0)

protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
{
    GridView gv = (GridView)sender;
    switch (e.CommandName)
    {
        case "delete":
            {
                    DataTable test = RetrieveData(0, 0); // this is a function I used to get a datatable
                    test.Rows[0].Delete();
                    test.AcceptChanges();
                    TargetedSpView = test.DefaultView;
                    TBDSPCGrid.DataSource = TargetedSpView;
                    TBDSPCGrid.DataBind();
            }
            break;
}
}