Button Controls

The Web controls family includes three types of button controls: Button, LinkButton, and ImageButton. Functionally, all three do exactly the same thing: they submit the form that hosts them to the server. The difference lies in their physical appearance. A Button control looks like a push button, a LinkButton looks like a hyperlink, and an ImageButton renders itself using an image you supply. Nearly every Web form uses one or more buttons to enable the user to submit the form to the server.

The following statements declare an instance of each control type in a Web form:

<asp:Button聽Text="Sort" RunAt="server" />
<asp:LinkButton聽Text="Sort" RunAt="server" />
<asp:ImageButton聽ImageUrl="sort.jpg" RunAt="server" />

The Text property specifies the text that appears on the face of a Button or LinkButton. ImageUrl identifies the image displayed by an ImageButton.

All three button controls fire two kinds of events when clicked: a Click event and a Command event. An OnClick attribute in the control tag wires a button to a Click handler. Click handlers for Button and LinkButton controls are prototyped this way:


But Click handlers for ImageButton controls are prototyped like this:


The ImageClickEventArgs passed to an ImageButton鈥檚 Click handler contains public fields named X and Y that specify where in the image the click occurred. X and Y are measured in pixels and represent distances from the image鈥檚 upper left corner.

Using Command events rather than Click events affords the developer the opportunity to pass additional information via the control鈥檚 CommandName and CommandArgument properties. The following example assigns the command name 鈥淪ort鈥?and the command argument 鈥淎sc鈥?to a Button control and toggles the command argument between 鈥淎sc鈥?and 鈥淒esc鈥?to perform alternating ascending and descending sorts:

<asp:Button聽Text="Sort" ID="SortButton" OnCommand="OnSort"
聽聽CommandName="Sort" CommandArgument="Asc" RunAt="server" />
<script聽language="C#" runat="server">
聽聽聽聽聽聽if聽(e.CommandName聽== "Sort" &&
聽聽聽聽聽聽聽聽聽聽e.CommandArgument.ToString聽()聽== "Asc")聽{
聽聽聽聽聽聽聽聽聽聽SortButton.CommandArgument聽= "Desc";
聽聽聽聽聽聽else聽if聽(e.CommandName聽== "Sort" &&
聽聽聽聽聽聽聽聽聽聽e.CommandArgument.ToString聽()聽== "Desc")聽{
聽聽聽聽聽聽聽聽聽聽SortButton.CommandArgument聽= "Asc";

Command events are useful for 鈥渙verloading鈥?button controls and having them perform different actions based on the value of CommandArgument. They can also be used to connect multiple buttons to a single handler and have the handler respond differently depending on which button was clicked.