HOWTO: Create a web control that handles a postback

Step 1:
Create a WebControl that implements the IPostBackEventHandler interface.

In my example I’ve created a CustomButton control that is a HTML <span> element that acts like a real button by trigging a postback and firing a Click event.

public class CustomButton : WebControl, IPostBackEventHandler
{
	public CustomButton()
	{
	}

	public void RaisePostBackEvent(string eventArgument)
	{
	}

	protected override void Render(HtmlTextWriter writer)	{
		base.Render (writer);
		writer.WriteBeginTag("span");
		writer.WriteAttribute("class", this.CssClass);
		writer.Write(HtmlTextWriter.TagRightChar);
		writer.Write(this.Text);
		writer.WriteEndTag("span");
	}

	private string _text;
	public string Text
 	{
		get { return _text; }
		set { _text = value; }
	}
}

Step 2:
Add clientside script to the control’s HTML so it can trigger a postback to the server.

In this example I want the button to post back when it’s clicked so I added an OnClick attribute to the button’s HTML element that contains the javascript code needed to do a postback.

There’s even a nice method of the Page object called GetPostBackClientEvent() that will automatically generate the postback clientside code for you if you pass a reference to the control that will be handling the postback and any arguments that you want to be passed back. Arguments are particularly useful for controls with more than one postback event.

protected override void Render(HtmlTextWriter writer)
{
	base.Render (writer);
	writer.WriteBeginTag("span");
	writer.WriteAttribute("class", this.CssClass);
	writer.WriteAttribute("onclick", Page.GetPostBackClientEvent(this, string.Empty));
	writer.Write(HtmlTextWriter.TagRightChar);
	writer.Write(this.Text);
	writer.WriteEndTag("span");
}

Step 3:
Create an event in your control to notify other controls that the postback event has occurred. We’ll create a Click event for our CustomButton.

public event EventHandler Click;
protected virtual void OnClick(EventArgs e)
{
	if(Click != null)
	{
		Click(this, e);
	}
}

Step 4:
Put code in your RaisePostBackEvent method to fire the event you’ve just created when the control causes a postback.

public void RaisePostBackEvent(string eventArgument)
{
	OnClick(EventArgs.Empty);
}

Step 5:
Add the button to a webpage and enjoy postback goodness!

Posted on 24 Oct 05 by Helen Emerson (last updated on 24 Oct 05).
Filed under Server controls