Determining which control has the focus on my web page

Discussion in 'ASP .Net Web Controls' started by deane_gavin, Apr 25, 2006.

  1. deane_gavin

    deane_gavin Guest

    I'm developing a simple ASP.Net web page in Visual Web Developer 2005
    Express. I know in my VB.Net code I can call the SetFocus method of my
    page to set the focus to any control. But is there a way of determining
    which web control currently has the focus? GetFocus would seem a nice
    choice for the name but it doesn't exist.

    I've scoured the .Net Framework Class Library documentation and the
    internet and I've not found any way of doing what I want. Of course,
    it's always possible I've missed something obvious.

    I think the question is simple enough that the above makes it clear
    (without, e.g., code examples) but if that's not enough information,
    please let me know what clarification is needed.

    Gavin Deane
    deane_gavin, Apr 25, 2006
    1. Advertisements

  2. hi Gavin, I see some built in functionality in .net already that should be
    detecting the last focus element since when setting focus on an element I
    find it including a hidden field in my form as :
    <input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />

    and some clientside code is also injected into the page :


    In effect these two resource files have some clientside js methods that set
    __LASTFOCUS, you can either try to call these js methods in the resource
    files or simply do it yourself with minimum code.

    there are many things you can do like for eg. you could add the onfocus
    attribute to a text box and specify some
    JavaScript code to configure what happens when the text box gets focus in
    the page. something like mytextbox.Attributes.Add("onfocus",

    This should set the id of the current textbox with focus into the
    __LASTFOCUS hidden field available on the page, which you can later lookup
    serverside. This means you must set it on every textbox or anyother control
    for whom you wish to know later in serverside code, this is the simplest
    way you can do it i guess.

    On the server side you can check for the __LASTFOCUS hiddenfield and findout
    what value is stored in there(obviously it will be the textbox who received
    the focus last)

    protected void Page_Load(object sender, EventArgs e)

    if (Request.Form["__LASTFOCUS"] != null)

    Have a fine day,
    Alessandro Zifiglio
    Alessandro Zifiglio, Apr 25, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.