TCM
TCM

Reputation: 16900

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 passing it to my delete method. Why is the DataItem always null and what can I do to get back my entity?

Upvotes: 0

Views: 951

Answers (3)

Piotr Perak
Piotr Perak

Reputation: 11098

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

Upvotes: 2

Tomas Voracek
Tomas Voracek

Reputation: 5914

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

Upvotes: 1

Amit
Amit

Reputation: 22086

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; 

Upvotes: 0

Related Questions