Online courses in ASP.NET MVC, ASP.NET Core, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC, ASP.NET Core, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Handling Post Back Events

Introduction

Post back data is not the only thing that you may want to deal with in your custom controls. You may want your control to cause a post back and raise some server side event such as Click or SelectedIndexChanged. Handling a post back event requires that your control implements IPostBackEventHandler interface. In this article I explain how that can be done.

IPostBackEventHandler Interface

The IPostBackEventHandler interface must be implemented by your custom control class if it requires to handle post back event. This interface contains a single method as shown below:

void RaisePostBackEvent(string eventArgument)

The PaisePostBackEvent() method gives you a chance to raise a server side post back event (e.g. Click or SelectedIndexChanged). The method receives an event argument  parameter of type string which may contain event argument data if any.

Example

Let's create a simple custom control that implements IPostBackEventHandler interface and raises Click event upon post back. Begin by creating a new web site in Visual Studio.

Add App_Code to your web site and further add a new class named GraphicButton. The following code shows the class definition.

namespace BinaryIntellect.UI
{
public class GraphicButton : WebControl, IPostBackEventHandler
{
public GraphicButton(): base(HtmlTextWriterTag.Span)
{

}
...

Here, you create a class named GraphicButton that resides in BinaryIntellect.UI namespace. The GraphicButton class inherits from WebControl base class and implements IPostBackEventHandler interface. The constructor of GraphicButton class calls its base class constructor by passing HtmlTextWriterTag. This indicates that your control builds over <SPAN> tag.

Now add two public properties viz. ImageUrl and Text to the GraphicButton class.

public string ImageUrl
{
get { return ViewState["imgurl"] as string; }
set { ViewState["imgurl"] = value; }
}

public string Text
{
get { return ViewState["text"] as string; }
set { ViewState["text"] = value; }
}

The ImageUrl property specifies the image URL to be displayed and Text property specifies the text to be rendered. Both of the property values are stored in ViewState. Then declare Click event as shown below:

public event EventHandler Click;

The Click event is raised when user clicks on the image rendered by the GraphicButton control. Now override the RenderContents() method of the WebControl base class and emit the required markup.

protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
writer.WriteFullBeginTag("center");
writer.WriteBeginTag("img");
writer.WriteAttribute("name", this.UniqueID);
writer.WriteAttribute("src", ImageUrl);
writer.WriteAttribute("onclick", 
Page.ClientScript.GetPostBackEventReference
(this, string.Empty));
writer.Write("/>");
writer.Write("<br />");
writer.Write(Text);
writer.WriteEndTag("center");
}

Here, we render an image tag and set its name and src attributes. It also renders the Text property value below the image. In order that the image tag triggers a post back event you need to handle its client side onclick event handler. Notice the call to GetPostBackEventReference() method. This method returns a javascript function (__doPostBack()) that actually causes the post back. The GetPostBackEventReference() method accepts two parameters viz. the control that will receive the post back and event arguments if any. If you supply some event arguments then they will be passed on to RaisePostBackEvent() method.

Finally, implement the IPostBackEventHandler interface by writing RaisePostBackEvent() method.

public void RaisePostBackEvent(string eventArgument)
{
Click(this, EventArgs.Empty);
}

Here, you simply raise the Click event of GraphicButton control.

This completes the control. In order to use it on a web form register it with the page framework as shown below:

<%@ Register 
Namespace="BinaryIntellect.UI" 
TagPrefix="mycontrols" %>

Also create an instance of the GraphicButton control on the web form.

<mycontrols:GraphicButton runat="server" ID="button1" 
Text="Save changes to database" 
ImageUrl="SaveButton.gif" 
onclick="button1_Click"
Font-Bold="True" /> 

Set the ImageUrl and Text properties to some image URL and text respectively and run the web form. Handle the Click event of the GraphicButton as follows:

protected void button1_Click
(object sender, EventArgs e)
{
Label1.Text = "Button clicked";
}

The following figure shows a sample run of the web form.

 




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 31 Dec 2007



Tags : ASP.NET Custom Controls