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:

void聽OnClick聽(Object聽sender,聽EventArgs聽e)
{
聽聽聽聽//聽Event聽handling聽code聽goes聽here
}

But Click handlers for ImageButton controls are prototyped like this:

void聽OnClick聽(Object聽sender,聽ImageClickEventArgs聽e)
{
聽聽聽聽//聽Extract聽the聽click聽coordinates
聽聽聽聽int聽x聽=聽e.X;
聽聽聽聽int聽y聽=聽e.Y;
}

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">
聽聽void聽OnSort聽(Object聽sender,聽CommandEventArgs聽e)
聽聽{
聽聽聽聽聽聽if聽(e.CommandName聽== "Sort" &&
聽聽聽聽聽聽聽聽聽聽e.CommandArgument.ToString聽()聽== "Asc")聽{
聽聽聽聽聽聽聽聽聽聽//聽TODO:聽Perform聽ascending聽sort
聽聽聽聽聽聽聽聽聽聽SortButton.CommandArgument聽= "Desc";
聽聽聽聽聽聽}
聽聽聽聽聽聽else聽if聽(e.CommandName聽== "Sort" &&
聽聽聽聽聽聽聽聽聽聽e.CommandArgument.ToString聽()聽== "Desc")聽{
聽聽聽聽聽聽聽聽聽聽//聽TODO:聽Perform聽descending聽sort
聽聽聽聽聽聽聽聽聽聽SortButton.CommandArgument聽= "Asc";
聽聽聽聽聽聽}
聽聽}
</script>

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.