Another cool nudge: maintaining the selection of an element when using paging
This is one of those simple things which really improves the use of controls like GridView and ListView. ASP.NET 4.0 adds the EnablePersistedSelection property to the GridView and ListView controls. To support this feature, the control ended up adding a new field (_persistedDataKey) which is saved in the control state of the control. Notice that what is persisted is the key that uniquely identifies the selected item (and not its position in the rows displayed by the grid.
When the grid needs to create its rows, it will update the SelectedIndex (and other associated props) by checking the data key of each item it is rendering against the value persisted in the _persisteDataKey field. What this means is that when you change the page and go to a new one that doesn’t have the previous selected item, you’ll end up getting –1 for the SelectedIndex property. I guess this isn’t really the behavior you’d expect, but I’m assuming that it wasn’t changed so that it was backward compatible with previous versions (or it might end up breaking existing code). To recover the current selected item you’ll have to use the new SelectedPersistedKey property (which returns a DataKey object associated with the item that has been selected).
And that’s it for now. Keep tuned for more on ASP.NET.