开发者

How to check to see if a textbox is currently active or has focus?

开发者 https://www.devze.com 2023-01-19 16:44 出处:网络
In C#, is it possible to get a bool value, determining if the cursor is currently inside a certain textbox?

In C#, is it possible to get a bool value, determining if the cursor is currently inside a certain textbox?

What I want to achieve:

I have a masterpage, with two buttons in it; a search-button and a login-button. Depending on what textbox is active or has focus, or of none have focus, I want to set the UseSubmi开发者_运维百科tBehavior-attribute.

What I want to happen is something like this (I know this code doesn't work):

if (textboxUsername.hasfocus == true || textboxPassword.hasfocus == true)
{
    buttonLogin.UseSubmitBehavior = true;
    buttonSearch.UseSubmitBehavior = false;
}
else
{
    buttonLogin.UseSubmitBehavior = false;
    buttonSearch.UseSubmitBehavior = true;
}

The goal is to make the page react the way the user expect it to, e.g. actually searching when hitting enter, and not trying to login, when you are typing in the search-field.


What you are trying to do won't work like that.

What you can do however is enclosing the login fields in a panel and the search field in a panel, and then you add a DefaultButton to both of them.

<asp:Panel runat="server" ID="SearchPanel" DefaultButton="Search">
    <asp:TextBox runat="server" ID="SearchInput" />
    <asp:Button runat="server" ID="Search" />
</asp:Panel>

If you press enter in this textbox the search button will do the postback.

Note: this does not work with LinkButtons or ImageButtons, if you use these you can add a workaround: add a normal Button and set it's style to display:none; and let the LinkButton and Button trigger the same event.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号