Jul 15 2005

Define an Event Handler for a HyperLink Server Control

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 06:55

Hello, a common question on the ASP.NET Forum is:

How to define an Event Handler for a HyperLink?

The solution as follows:

protected System.Web.UI.WebControls.HyperLink HyperLink1;
    
private void Page_Load(object sender, System.EventArgs e)
{
    HyperLink1.Attributes.Add("onClick",
Page.GetPostBackEventReference(this.HyperLink1,"HyperLinkPostBack$"+this.HyperLink1.ID)); if ( (IsPostBack) && (Request.Form["__EVENTTARGET"] != null) && (Request.Form["__EVENTARGUMENT"].ToString().StartsWith("HyperLinkPostBack")) ) { string[] args = Request.Form["__EVENTARGUMENT"].ToString().Split('$'); if ( (string.Compare(args[0], "HyperLinkPostBack", false, System.Globalization.CultureInfo.InvariantCulture) == 0)
&& (args.Length > 1) ) { HyperLinkHandler(args[1].ToString()); } } } public void HyperLinkHandler(string ID) { Response.Write("You clicked HyperLink with ID : "+ ID); }

              
 

              
 
 Or You could use this way, using IPostBackEventHandler:

              
private void Page_Load(object sender, System.EventArgs e)
{
    HyperLink1.Attributes.Add("onClick", Page.GetPostBackEventReference(this, "HyperLinkPostBack" + "$" + this.HyperLink1.ID));
}

public void RaisePostBackEvent(string eventArgument)
{
    if (!string.IsNullOrEmpty(eventArgument))
        {
            string[] args = eventArgument.Split('$');
                if ((string.Compare(args[0], "HyperLinkPostBack", false, System.Globalization.CultureInfo.InvariantCulture) == 0) 
&& (args.Length > 1)) { HyperLinkHandler(args[1].ToString()); } } } public void HyperLinkHandler(string ID) { Response.Write("You clicked HyperLink with ID : " + ID); }

              
 

Hope that helps,

Regards

Tags: ,

Comments are closed