【问题标题】:grdview_RowDeleting DataItem is Nullgrdview_RowDeleting DataItem 为 Null
【发布时间】:2011-05-21 13:05:05
【问题描述】:

我已将我的数据网格绑定到一个列表。我正在遵循存储库模式并使用 EF v4.1。我需要在 row_deleting 事件中删除实体。这是代码:

    protected void grdBooks_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        int bookId = (int)e.Keys[0];
        //grdBooks.Rows[e.RowIndex] //this item's dataItem is always null.
    }

当我使用实体时,我需要实际的实体将其传递给我的 GenericRepository,这将删除该实体。我确实得到了 bookId,但我不想做一些愚蠢的事情,比如使用这个 bookId 从数据库中获取实体,然后将其传递给我的删除方法。为什么 DataItem 总是为空,我该怎么做才能取回我的实体?

【问题讨论】:

    标签: c# asp.net entity-framework gridview aspxgridview


    【解决方案1】:

    DataItem = null 因为当您在 Page_Load 中仅将数据绑定到 gridview 一次时

    public void Page_Load()
    {
        if (!Page.IsPostBack)
        {
            grid.DataSource = GetDataSource();
            grid.DataBind();
        }
    }
    

    数据存储在 Viewstate 中。单击删除后,您将回发到服务器。数据仍然存在于 Gridview 的 viewstate 中并且不会反弹。

    如果您有 ID,您可以删除该对象。您可以通过 3 种不同的方式做到这一点

    1. http://blogs.msdn.com/b/alexj/archive/2009/03/27/tip-9-deleting-an-object-without-retrieving-it.aspx

    2. 调用 context.ExecuteStoreCommand 并执行常规的 DELETE FROM -http://msdn.microsoft.com/en-us/library/ee358769.aspx(第二个示例)

    3. 在数据库上创建存储过程,将其导入模型并使用 context.ExecuteFunction() 调用它

    【讨论】:

      【解决方案2】:

      您无需获取任何内容即可将其删除。只需创建具有指定 Id 的实体,附加它,然后调用 Remove。

      Person user = new Person() { PersonId = Id };
      db.Persons.Attach(person);
      db.Persons.Remove(person);
      db.SaveChanges();
      

      【讨论】:

      【解决方案3】:

      我不知道我是否正确理解了你的问题,但我认为你应该试试这个

      grdBooks.Rows[e.RowIndex].Cells[index].Text; 
      

      【讨论】:

      • @Thomas:- 我想从按下删除按钮的行中获取实体。你明白了吗?如果您仍然没有得到它,请告诉我。我会以更好的方式完整地解释我的问题。
      猜你喜欢
      • 2015-02-21
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      相关资源
      最近更新 更多