Jerry
Jerry

Reputation: 6557

OnTextChanged loses focus when AutoPostBack is true

I have a ASP.Net webform that has several textboxes. Some of the textboxes have an OnTextChanged event with AutoPostBack set to true.

When the user enters some text and leaves the textbox, I want some code to run. This part works fine.

The problem is that if a user enters some text, then clicks or tabs to another textbox, the OnTextChanged of the current textbox event fires fine but the textbox that the user clicked on does not keep focus. This causes problems because the user thinks they are on the next textbox but they aren't. And no object seems to have the focus.

Is there anything that can be done to make the next object keep focus while the OnTextChanged event of the current textbox fires?

Upvotes: 3

Views: 11817

Answers (2)

Mateus Schneiders
Mateus Schneiders

Reputation: 4903

One option is to use <asp:UpdatePanel> Control.

Facts about using it:

  • The postback request would be made via AJAX.
  • It would not recreate the whole page HTML.
  • When the UpdatePanel updates, it replaces the DIV innerHTML, that would make the textbox lose focus (bad point).
  • To maintain the focus, you would have to avoid the UpdatePanel from updating when the textbox posts back.
  • You can avoid the update by setting the UpdateMode and ChildrenAsTriggers properties.

Here is an example:

<asp:UpdatePanel ID="uppTextboxes" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
    <ContentTemplate>
        <asp:TextBox ID="txb1" runat="server" AutoPostBack="true" OnTextChanged="txb1_OnTextChanged" />
        <asp:TextBox ID="txb2" runat="server" />
    </ContentTemplate>
</asp:UpdatePanel>

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460168

Since the whole page is recreated on postback on serverside and the browser will recreate all html on clientside, you have to tell ASP.NET that your TextBox needs focus.

Use Page.SetFocus:

Page.SetFocus(IdOfControl);

However, i would prefer not to postback at all if i can. Can't you use a button that the user has to click after he has entered all necessary data?

Upvotes: 4

Related Questions