Status of Asp.Net GridView EditIndex?

This is a bit of a hypothetical question that sent me down a garden path ... Let's say I have a gridview that I would like to edit ... using a method that links the data.

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

Now suppose I look at this page and another user comes in and makes some changes to the base data, and now I go to the edit button and edit D ..

The editing method is quite simple:

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

Edit: I feel compelled to indicate that this method is used in almost all online examples, including Microsoft.

This BindGridSecond () method looks like this:

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

This is exactly the same, but the data is now changed. After updating the user interface, the user is now in edit mode on line C.

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

+4
source share
2 answers

Personally, I use the DataKeyNames and SelectedDataKey properties in the GridView, so that I can easily get the primary key of the row that the user wants, instead of relying on the grid index.

Using the primary key, you have no problem adding new elements to the collection, for example, in your example. In addition, the use of a primary key makes it easier to work with a search call in the grid, since you do not need to consider the page number and index.

+1
source

IMHO there are two options:

You can cache the data you want to snap to the grid in the session, for example. That way, you can check the changes before you call the BindGridSecond method, and alert the user if any changes were made while viewing the page.

In option 2, you will again cache the data that was bound in the BindGridFirst-Method, and simply work with this data for the next PostBack actions. Therefore, you do not need to worry about the changes that may occur when viewing the grid.

0
source

All Articles