Showing posts with label controls. Show all posts
Showing posts with label controls. Show all posts

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