IButtonControl – any button will do

One nice feature of ASP.NET 2.0 is a new interface called IButtonControl. You can use it in a code behind to say a control needs to be a button but without actually saying whether it needs to be a Button, LinkButton, ImageButton or custom control button type.

This is the type of thing that’s useful if you have a code behind used by multiple different aspx pages, each with slightly different requirements of what the button should look like. It also means you can switch between the three without having to change the code behind.

So instead of a huge ugly if statement like this:

Button button = Page.FindControl("Button1") as Button;
ImageButton imageButton = Page.FindControl("ImageButton1") as ImageButton;
LinkButton linkButton = Page.FindControl("LinkButton1") as LinkButton;
if(button != null)
    button.Text = "Click me";
else if(imageButton != null)
    imageButton.Text = "Click me";
else if(linkButton != null)
    linkButton.Text = "Click me";

Instead you can support all three scenarios nice and simply like this:

IButtonControl button = Page.FindControl("Button1") as IButtonControl;
button.Text = "Click me";

It’s implemented by all the built in button controls (Button, ImageButton, LinkButton) and has all the common button functionality like the Click event, the CommandArgument and support for validation.

Posted on 30 Jun 08 by Helen Emerson (last updated on 30 Jun 08).
Filed under ASP.NET, Server controls