Persisting Row Selection in Data Controls - .NET 4

In .NET 4, we can maintain the row selection in data controls while paging or sorting. That's a cool feature available in .NET 4. You will be amazed after enabling this property in your data controls.
 
In previous version of .NET, if you select the 2nd row in the page 1 and navigating to the page 2, do you remember what will happen? 2nd row in the page 2 will be selected. Reason behind this issue is previous version row selection are purely based on the row index.
 
Persisted selection was initially supported in dynamic data projects in .NET 3.5 PS1.
 

How it works in .NET 4?

 
When this property is enabled in the data controls, the currently selected item is based on the data key items. That's the reason when you navigate to another page, selection won't be there in that page. When you come back again to the selected row in page 1, surely the selection will be persisted because of the data key. This property is supported in GridView and ListView.
 
Example:
 
<asp:GridView id="GridView2" runat="server" EnablePersistedSelection="true">
</asp:GridView>
 
Note:
 
Don't forget to add the DataKeyNames when you enable this property, since the property is fully based on the DataKeyNames associated with the row.
 
Even though it's a simple feature, it adds more clarity to the selection based grid functionality in a web page.
 
Pictorial Explanation – Previous Versions to .NET 4
 
Select 1st row in page 1, 1st row will be selected.
 
Fig1.gif
 
Go to page 2, again the 1st row in that page will be selected.
 
Fig2.gif
 
Pictorial Explanation – In .NET 4
 
Select 1st row in page 1, 1st row will be selected.
 
Fig3.gif
 
Go to page 2, here 1st row wont get selected, because here its purely based on the DataKey.
 
Fig4.gif
 
Again move back to 1st page, selection will be persisted
 
Fig5.gif
 
That's the cool feature of .NET4.