views:

44

answers:

2

This is a bit of a hypothetical question that has sent me off down the garden path... Say I have a gridview that I'd like to edit... given a method that binds the data..

private void BindGridFirst() {
        var data = new List<string>() {
            "A","B","C","D","E","F"
        };
        gridView.DataSource = data;
        gridView.DataBind();
    }

Now presume that I'm looking at this page, and another user has come along and made some changes to the underlying data, and I now go and click the edit button to edit D...

The edit method is pretty straight forward:

protected void RowEdit(object sender, GridViewEditEventArgs e) {
        gridView.EditIndex = e.NewEditIndex;
        BindGridSecond();
    }

Edit: I feel compelled to point out, that this method is used in pretty much all the online examples, including ones from Microsoft.

This BindGridSecond() method looks like so:

private void BindGridSecond() {
        var data = new List<string>() {
            "A", "AA", "B","C","D","E","F"
        };
        gridView.DataSource = data;
        gridView.DataBind();
    }

It's exactly the same, but the data is now changed. Once the UI updates, the user is now in edit mode against row C.

Not what the user expected or wanted. How should this scenario be handled to avoid such an issue?

A: 

Imho there are two options:

You could cache the Data you want to bind to the Grid in a Session for example. So you are able to check for changes before you call the BindGridSecond-Method and alert the user if any changes have been made while he was browsing the Page.

In option 2 you would again cache the Data you were binding in the BindGridFirst-Method and just work with this data for the next PostBack actions. So you don't have to worry about changes that may occur while browsing the Grid.

Dave
A: 

Personally, I use the DataKeyNames property and the SelectedDataKey on the GridView, so that I can easily obtain the primary key of the row the user wants, rather than relying on the index of the grid.

By using the primary key, you don't have any issues with new items being added to the collection, such as in your example. Plus, using the primary key makes it easier to deal with paging on the grid, as you don't have to take the page number and index into account.

Jason Berkan