In this article I will explain with an example, how to trigger TextBox OnBlur event on Server Side (Code-Behind) in ASP.Net with C# and VB.Net.
By default, there is no Server Side OnBlur event and the only similar event is provided by ASP.Net is TextChanged event but TextChanged event fires only when Text is changed while OnBlur event fires when Focus is lost despite whether Text is changed or not.
Triggering TextBox OnBlur event on Server Side (Code-Behind) in ASP.Net
HTML Markup
The HTML Markup consists of an ASP.Net TextBox and a LinkButton.
The LinkButton has been assigned with OnClick event handler.
Note: Since there is no Server Side OnBlur event, a Hidden LinkButton is used and its OnClick event handler will be triggered using JavaScript inside the Client Side OnBlur event of the TextBox.
The TextBox has been assigned with a Client Side OnBlur event handler which calls the JavaScript function OnBlur.
Triggering Server Side (Code-Behind) event handler with TextBox OnBlur event
When Focus is set out from the TextBox, the Client Side OnBlur event calls the JavaScript function OnBlur which references the LinkButton using its ID and then calls its Client Side Click event which in turn does PostBack and calls the Server Side (Code-Behind) Click event handler of the LinkButton.
<form id="form1" runat="server">
<asp:TextBox ID="txtName" runat="server" onblur = "OnBlur();"/>
<asp:LinkButton id="lnkHidden" runat="server" OnClick="OnBlur" />
<script type="text/javascript">
function OnBlur() {
document.getElementById("lnkHidden").click();
};
</script>
</form>
Handling the OnBlur event in Server Side (Code-Behind)
Inside the OnBlur event handler, a JavaScript Alert Message Box is displayed.
C#
protected void OnBlur(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('OnBlur Fired.');", true);
}
VB.Net
Protected Sub OnBlur(sender As Object, e As System.EventArgs)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('OnBlur Fired.');", True)
End Sub
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads