从c#中的视图状态中删除特定项

时间:2015-03-22 13:08:40

标签: c# asp.net c#-4.0

我正在关注how to insert data in to grid view using asp.net without database教程。

但是我使用了不同的属性,比如

[Serializable]
public class feilds
{
    public string DocumentId { get; set; }
    public string Document { get; set; }
    public string FileName { get; set; }
    public byte[] FileContent { get; set; }
    public string URL { get; set; }
    public bool IsActive { get; set; }
}

我在网格中有其他模板项

      <asp:GridView ID="grdDummy" OnRowCommand=" grdDummy_RowCommand" runat="server">
                  <Columns>
                 <asp:TemplateField HeaderText="Delete">
                 <ItemTemplate>
                 <asp:LinkButton ID="lnkDelete" runat="server" CssClass="colorlnkbtndelete"  CommandName="Delete" CommandArgument='<%# DataBinder.Eval (Container.DataItem, "DocumentId") %>'><i class="icon-trash"></i></asp:LinkButton>
              </ItemTemplate>
              </asp:TemplateField>
              </Columns>      
               </asp:GridView>

现在我希望当我们点击删除链接按钮时,应该从视图状态删除相应的项目,然后再删除网格。

我试过以下

    protected void grdDummy_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            string docid = e.CommandArgument.ToString();
            feilds s = new feilds();
            int index = data.FindIndex(s.DocumentId docid);
            data.RemoveAt(index);
            ViewState["_data"] = data;

        }
    }

它无法正常工作!

1 个答案:

答案 0 :(得分:0)

这是一种可能的方式:

protected void grdDummy_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        string docid = e.CommandArgument.ToString();
        //find field by documentId and remove it from list
        data.Remove(data.Find(o => o.DocumentId == docid));

        ViewState["_data"] = data;

        //rebind grid
        grdDummy.DataSource = data;
        grdDummy.DataBind();
        e.Handled = true;
    }
}

顺便说一下,您的命令参数可以缩短为:

CommandArgument='<%# Eval("DocumentId")%>'