Understanding the Common Features of Web Controls
Before diving into the details of Web controls, you should survey the entire collection of Web controls offered in ASP.NET, as shown in Figure 4.1.
Figure 4.1 ASP.Net Web Controls ready for use in you own applications.
Notice that Web controls fall into three main groups:
Controls such as Button, TextBox, Label, and DropDownList are thinwrappers around the standard HTML controls. A wrapper for an object issome code in a library that allows you to program with that object more easily.For example, the TextBox, Label, and DropDownList controls help you produce thecorresponding HTML controls more easily.
Validation controls have no HTML equivalent. They allow you to includevalidation rules and error messages that trigger based on the contents of othercontrols on the page.
Data display controls allow you to create more complex interaction inyour Web pages. They create complex HTML output and save you time for many datadisplay tasks.
You can pick from several Web controls, and each has numerous methods,properties, and events. To tackle learning all of them, let's explore whatall the controls have in common.
Common Events
All ASP.NET controls expose events that you can handle with server-side code.Events work by having the ASP.NET page post form variables to itself after auser action. Undercover, ASP.NET generates a small amount of client-sideJavaScript that will generate a form submit request when a control is activated.As a result, you must use the <form runat="server"> tagin any ASP.NET page that uses events.
Table 4.1 shows the most common events a typical ASP.NET page can handle.
Table 4.1—Commonly Handled Events from Web Controls
Event |
Description |
Click |
The Button, HyperLink, ImageButton, and LinkButton controls send this event when users click them. |
SelectedItemChanged |
The ListBox, DropDownList, CheckBoxList, and RadioButtonList controls send this event when the selected item is changed. |
CheckChanged |
The CheckBox control sends this event when the control becomes checked or unchecked. |
Handling a Web control event involves two steps:
Specify the name of the event you want to handle. Of course, the event name must be an event that the control can send. To specify an event, prepend On to the event name and add the name of the event handling method in code. To specify the Click event for a Button control, you might use code like the following:
Write the event handler. From the preceding line, you would need to write code like the following:
<asp:Button id="MyButton" OnClick="ClickEventHandlingMethod" runat="server" />
void ClickEventHandlingMethod(Object sender, Eventargs e) { //code that takes some action }
The Calendar, DataList, and DataGrid controls have special events that I cover tomorrow.
Other Events
All controls can fire several other events (see Table 4.2). You probably won't handle these events as frequently in your code, but they are worth a quick look.
Table 4.2—Other Events in ASP.NET Web Controls
Event |
Description |
Init |
Called when the control is initialized. This is the first event called for every control. |
Load |
Called when the Page object loads the control. |
PreRender |
Called right before the control is rendered into the HTML result stream. |
DataBinding |
Called when the control is bound to a data source. |
Disposed |
Called when the control is released from memory. This call can happen at any time after the page is fully rendered, when the .NET garbage collector runs. |
Every Web control inherits these events from the Control class. Notice that some events are similar to the events in the Page class. This is no coincidence—the Page class is derived from the Control class.
The AutoPostBack Property
By default, list box controls and selection controls, such as a check box list, won't repost form data every time the user changes a selection. However, you can force these controls to repost data whenever their selection changes by setting the AutoPostBack property to true.
NOTE
If the client's browser supports DHTML, ASP.NET can render the Web controls so that events won't cause another hit to the server unless absolutely necessary. You don't have to worry about the DHTML details when writing code. However, for earlier browsers that don't support DHTML, each control event requires a round-trip to the Web server.
The sample in Listing 4.1 handles the events listed in Table 4.1.
Listing 4.1—HandleEvents.aspx: Handling Common Events in Some Web Controls
1: <html> 2: <body> 3: <script runat="server" language="C#"> 4: void ButtonPress(Object Sender, EventArgs e) 5: { 6: lblOutput.Text = "You pressed the button<br>"; 7: } 8: void MyDropSelected(Object Sender, EventArgs e) 9: { 10: lblOutput.Text = ExDrop.SelectedItem.ToString() + 11: " is selected in the drop down box<br>"; 12: } 13: void MyCheckSelChange(Object Sender, EventArgs e) 14: { 15: lblOutput.Text = ""; 16: for(int i=0; i < ExCheck.Items.Count; i++) { 17: if(ExCheck.Items[i].Selected) { 18: lblOutput.Text += "Check box " + i.ToString() + 19: " is checked<br>" ; 20: } 21: else { 22: lblOutput.Text += "Check box " + i.ToString() + 23: " is not checked<br>"; 24: } 25: } 26: } 27: </script> 28: <form runat="server"> 29: <asp:Button id="ExButton" text="Press Me" OnClick="ButtonPress" 30: runat="server"/> 31: <br> 32: <asp:DropDownList id="ExDrop" runat="server" 33: OnSelectedIndexChanged="MyDropSelected" 34: AutoPostBack="True"> 35: <asp:ListItem>Item 1</asp:ListItem> 36: <asp:ListItem>Item 2</asp:ListItem> 37: <asp:ListItem>Item 3</asp:ListItem> 38: </asp:DropDownList> 39: <br> 40: <asp:CheckBoxList id="ExCheck" runat="server" 41: OnSelectedIndexChanged="MyCheckSelChange" 42: AutoPostBack="True"> 43: <asp:ListItem>Check 1</asp:ListItem> 44: <asp:ListItem>Check 2</asp:ListItem> 45: <asp:ListItem>Check 3</asp:ListItem> 46: </asp:CheckBoxList> 47: <hr> 48: <asp:Label id="lblOutput" runat="server" /> 48: 50: </form> 51: </body> 52: </html>
In Listing 4.1, the DropDownList and CheckBoxList controls both use the ListItem subcontrol (Lines 32–38 and 40–46). Use ListItem to add entries to each control. ListItem is an example of a Web control contained within another Web control. You'll see other examples of contained Web controls in the next few lessons.
Each control in Listing 4.1 has its AutoPostback property set to "True" (Lines 34 and 42). This forced the control to repost the form data whenever the user selects a different item in the controls.
If you've written .NET code that handles events, the event handlers for each Web control in Listing 4.1 should look familiar. If you haven't, know that each event handler takes two parameters: the Sender and EventArgs objects. We don't use either object in Listing 4.1 because we can query each Web control for the currently selected item.
Control Properties
All ASP.NET Web controls share a set of common properties. Because there are several, we will explore the most common ones. Table 4.3 lists some of the more interesting common properties.
Table 4.3—Common Properties of Web Controls
Property |
Description |
ID |
The control's ID, which you can use to refer to the control in code. |
Parent |
The control's parent, which is usually the Page object. |
Visible |
If set to false, the control won't be displayed. Defaults to true. |
ToolTip |
Sets the ToolTip that's displayed when the user hovers the mouse pointer over the control. Not all browsers support this feature. |
Page |
The Page object, for convenience. |
Height, Width, ForeColor, BackColor, BorderColor, Font, Style, CssStyle |
I will cover these properties later in the "Beautifying Your Controls" section. |
Table 4.3 shows that each Web control can be manipulated as though it were a regular GUI control. For example, you can write code in the Page_Load event to set a control's Visible property to true or false depending on the application's needs.
Specific Properties of Web Controls
Several properties are specific to a few controls that you will use commonly in your ASP.NET applications (see Table 4.4).
Table 4.4—Properties Used with Web Controls
Property |
Description |
Text (set) |
Sets the text associated with the Label, ListItem, Button, ImageButton, LinkButton, and HyperLink controls |
Text (get) |
Receives the text associated with the ListItem control when calling the SelectedItem method of its parent |
Checked |
True if a CheckBox or RadioButton control is checked or selected |
Selected |
True if a ListItem control is selected in a ListBox, DropDownList, RadioButtonList, or CheckBoxList control |
Of course, the properties in Table 4.4 aren't the only ones you will use in your code. I will show examples of many others, and the Visual Studio documentation contains the full explanation of each property for each Web control.
Control Methods
All Web controls share two interesting methods: DataBind and ApplyStyle. ApplyStyle lets you apply a Style object to the control, to set the control's look and feel. I will cover this method later in the section "Beautifying Your Controls."
DataBind is handy for automatically displaying data in a control. The data can come either from properties in a class that you create or from an ADO.NET DataSet. On Day 12, "Using ADO.NET and ASP.NET Together," I will explain how to use Web controls and ADO.NET together to make interesting applications. Tomorrow, you will learn how to create complex data grid controls using the DataBind method.