How To: Use OnClientClick() for your button controls

September 8, 2006

I didn’t realize that this property exist up until today when i was playing with a custom control that i was building (don’t ask what control it is! ofcourse its a button). At first i don’t what to do with it since its something that was just injected in the .NET 2.0 framework but upon reading and understanding the method i realized that i could insert a javascript call inside this method call.. something similar to what i got used to doing which is adding attributes to the control at the page_init level.

Here’s the code listing of what i did:

The .aspx file

<%@ Page Language=“C#” AutoEventWireup=“true” CodeFile=“Default.aspx.cs” Inherits=“_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “”>

<html xmlns=“” >
<head runat=“server”>
<title>Keith’s OnClientClick Demo</title>
<form id=“form1” runat=“server”>
<asp:Button ID=“btnOne” runat=“server” OnClick=“btnOne_Click” Text=“Add Attribute” />
<asp:Button ID=“btnTwo” runat=“server” CausesValidation=“False” OnClick=“btnTwo_Click”
OnClientClick=“alert(‘Here you go! now you got an alert!’);” Text=“OnClientClick” /></div>

The code file:

using System;

public partial class _Default : System.Web.UI.Page
   protected void Page_Load(object sender, EventArgs e)
      if (!IsPostBack)
         btnOne.Attributes.Add(“onclick”, “javascript:alert(‘test!’);”);
   protected void btnOne_Click(object sender, EventArgs e)
   protected void btnTwo_Click(object sender, EventArgs e)

As you can see, we have accomplished the same results with what the Attributes.Add was able to accomplish by using the OnClientClick property.

Leave a Reply

Your email address will not be published. Required fields are marked *