开发者

grdview_RowDeleting DataItem is Null

I have bound my datagrid to a list. I am following Repository pattern and using EF v4.1. I need to delete the Entity on row_deleting event. This is the code:

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

As I am working with Entities, I need the actual Entity to pass it to my GenericRepository which will delete that entity. I did get the bookId but I don't want to do silly things like fetching the Entity from database using this bookId and then passi开发者_StackOverflow中文版ng it to my delete method. Why is the DataItem always null and what can I do to get back my entity?


DataItem = null because when You databind data to gridview only once in Page_Load

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

data is stored in Viewstate. After You click delete You postback to server. Data is still present in Gridview's viewstate and not rebound.

You can delete the object if You have Id. You can do it in 3 different ways

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

  2. call context.ExecuteStoreCommand and just do the regular DELETE FROM -http://msdn.microsoft.com/en-us/library/ee358769.aspx (2nd example)

  3. create stored procedure on database, import it to model and the call it using context.ExecuteFunction()


You do not need fetch anything to delete it. Just create Entity with specified Id, Attach it and then call Remove.

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


I am not suer whether I have understood your question right or not but I think you should try this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜