0

I'm trying to add an event handler to a TextBox control that is called when the text box loses focus. Is this possible?

I know WinForms has a LostFocus event. I'm looking for something similar in ASP.NET WebForms.

muttley91
  • 12,278
  • 33
  • 106
  • 160

3 Answers3

2

You can Use OnBlur

<asp:TextBox id="TextBox1" runat="server" onblur="Javascript:alert('1234');" />

Or EDIT: Server side

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Attributes.Add("onblur", "alert('hi User')");
    }
}
Dgan
  • 10,077
  • 1
  • 29
  • 51
  • Is it possible to call C# code at all with this method? – muttley91 Mar 19 '14 at 19:36
  • @rar you can add your server side code (C#) with above – Dgan Mar 19 '14 at 19:42
  • Do you mean add the JavaScript server side, or is there a way to add C# code to the onblur event? – muttley91 Mar 19 '14 at 19:57
  • If You want to Execute Something From Server Side then You can take One asp Button Make it display none and call its postback event onblur of textbox – Dgan Mar 19 '14 at 20:00
  • The server side solution doesn't seem to work if I want to add text from another page element. – muttley91 Mar 19 '14 at 21:04
  • if You Wants to Display Some Text from another Page Then You have to Maintain State at Server Side http://www.codeproject.com/Articles/492397/State-Management-in-ASP-NET-Introduction – Dgan Mar 20 '14 at 05:09
1

I think you are going to have to use javascript for this and the event you will need to search and look up would be onBlur() I believe. If you need an example, I might be able to scrounge one up for you. But here are some links..

W3Schools

Stack

Java Page

Hope these help.

Community
  • 1
  • 1
Humpy
  • 2,004
  • 2
  • 22
  • 45
0

This would be the blur event, and it's a client-side event on the resulting input element instead of a server-side event on the TextBox control.

For example, let's say you have a TextBox with the ID of "TextBox1", and let's assume jQuery is included in your project template (because it probably is), then in your client-side code you might have something like this:

$('#<%= TextBox1.ClientID %>').blur(function () {
    // code to respond to the event
});

This would execute any code in that function whenever the input for that TextBox control loses focus. Notice the use of a small block of server-side code to output the server-side control's client-side ID.

David
  • 208,112
  • 36
  • 198
  • 279