Maintaining focus across post backs is an apparently difficult task. Searching Google, you will find a ton of people that desire the same thing, but all hook it up differently, and mostly, custom-ly. I would like to avoid a custom implementation, especially if there's a way it's supported by .NET. Only after some very deep searching, did I come across PostBackOptions.TrackFocus, mentioned quietly in another stack overflow post. According to MSDN:
Gets or sets a value indicating whether the postback event should return the page to the current scroll position and return focus to the current control."
Holy crap, this is supported by .NET 4? AWESOME. But we have a ton of custom controls, how does .NET know how to set the focus on a control? I have no idea. Looking a the MSDN documentation for System.Web.UI.Control, there's an interesting method:
public virtual void Focus()
"Use the Focus method to set the initial focus of the Web page to the control. The page will be opened in the browser with the control selected."
Alright, clearly overridable. But what is the recommended method of doing so? It returns void. No examples. Unable to find any examples of people overriding this method in their implementations. However, after overriding it and doing nothing more than throwing an exception, it becomes evident that this is not how ASP.NET gets focus on a control that had focus before the post back: it never gets called.
After a ton of debugging using Firebug, I have found that enabling PostBackOptions.TrackFocus works! Sometimes. It is apparent that the focus of a control is only maintained when the control calls the __doPostBack JavaScript method. Other controls that launch a PostBack (when pressing enter inside the control), call WebForm_OnSubmit(), which doesn't update the ASP hidden field __LASTFOCUS. __doPostBack calls WebForm_OnSubmit() after setting the hidden fields.
This is where I'm currently stuck. It's looks as if I need to get everything to call __doPostBack, no matter what. There's very, very little documentation on the use of TrackFocus. So does anyone have any tips from here?