Friday, January 22, 2010

How to use events like onblur, onfocus, etc. for ASP.NET Texbox and other controls

Have you ever wondered if you can use other event attributes for some ASP.NET controls, say an ASP.NET Textbox?



When upon checking, all you see that's available is a TextChanged event. And you know that the html input tag can support other events like:


Source: w3schools



A workaround is to create an ASP.NET Button and place it inside a hidden div:

<div style="display: none;">
    <asp:Button ID="btnTextBoxEventHandler" runat="server"
    OnClick="btnTextBoxEventHandler_Click" />
</div>
 
And here's the markup for the textbox, just a regular one:

<asp:Textbox ID="txt1" runat="server" />

Now on your page onload event, add an attribute to your textbox:

protected void Page_Load(object sender, EventArgs e)
{
    txt1.Attributes.Add("onblur", this.Page.ClientScript.GetPostBackEventReference(this.btnTextBoxEventHandler, ""));
}

Then of course, the event handler for the button:

protected void btnTextBoxEventHandler_Click(object sender, EventArgs e)
{
    //Place code here for onblur..
}

Now place the code you want to trigger (when the textbox loses focus) inside the button event and see what happens. Try experimenting with other event attributes and ASP.NET control combinations too.


-k

10 comments:

  1. v r using onblur for the txt box validation ... after focus comes out from the txt box it should auto check the conduction with out click any button .........

    ReplyDelete
  2. Thanks alot. Really useful code.

    ReplyDelete
  3. perfect. Absolutely helped me:).

    ReplyDelete
  4. Gracias, excelente me sirvió al primer intento, saludos.

    ReplyDelete
  5. Thank you, I have wasted hours trying to get ASP.Net and Java to play nice.
    I am new to both so naturally thought I was the problem.

    ReplyDelete
  6. works like magic
    thank you very much!!!

    ReplyDelete
  7. thanks man !! your logic worked smoothly...
    i was searching a way to calculate amount and tax on change event.. This works perfectly..

    ReplyDelete