Maintain Control focus across post backs using PostBackOptions.TrackFocus

ⅰ亾dé卋堺 提交于 2019-12-06 00:39:14

I've been maintaining focus accross postbacks using the method in this article: (ie: store focus in __LASTFOCUS hidden field on field enter event clientside for all controls)

http://www.codeproject.com/KB/aspnet/MainatinFocusASPNET.aspx

If you've gotten as far as having __LASTFOCUS show up on the page, this should get you most of the rest of the way...

Note: It'd be nice to find a way to keep the extra javascript from bloating __VIEWSTATE for example.

It was working pretty well for me until I figured out that some of my pages included the hidden __LASTFOCUS field and some of my pages didn't. (That's what prompted me to search around and find your question) Now I'm just trying to figure out how to make sure __LASTFOCUS always shows up on every page I want to keep track of focus on... (Looks like I'll have to open a separate question about it)

Here is what I just did. Assuming you have a handler in your code behind that takes care of the event and has a signature like this:

protected void myEventHandler(object sender, EventArgs e)

You can use this line of code to restore focus back to the sending object:

        ScriptManager.RegisterStartupScript((WebControl) sender, sender.GetType(), "RestoreFocusMethod", "document.getElementById(\"" + ((WebControl) sender).ClientID + "\").focus();", true);

just using the Focus() method of the sending control will reposition the page (if you are scrolled down a bit), but this works beautifully. And if you have specific handlers for your control, you can just use the control itself rather than casting the sender to a WebControl, like this:

    protected void CityListDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        ...
        ScriptManager.RegisterStartupScript(CityListDropDown, CityListDropDown.GetType(), "CityDropDownRefocus", "document.getElementById(\"" + CityListDropDown.ClientID + "\").focus();", true);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!