Home > Articles


Like this article? We recommend

Understanding the Common Features of Web Controls

This article is excerpted from Chapter 4, "Working with Web Controls" of Sams Teach Yourself C# Web Programming in 21 Days, by Phil Syme and Peter Aitken (0672322358). Content is based on Beta 2 version of Microsoft's .NET technology.

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 thin wrappers around the standard HTML controls. A wrapper for an object is some 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 the corresponding HTML controls more easily.

  • Validation controls have no HTML equivalent. They allow you to include validation rules and error messages that trigger based on the contents of other controls on the page.

  • Data display controls allow you to create more complex interaction in your Web pages. They create complex HTML output and save you time for many data display 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 what all 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 a user action. Undercover, ASP.NET generates a small amount of client-side JavaScript that will generate a form submit request when a control is activated. As a result, you must use the <form runat="server"> tag in 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




The Button, HyperLink, ImageButton, and LinkButton controls send this event when users click them.


The ListBox, DropDownList, CheckBoxList, and RadioButtonList controls send this event when the selected item is changed.


The CheckBox control sends this event when the control becomes checked or unchecked.

Handling a Web control event involves two steps:

  1. 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:

  2. <asp:Button id="MyButton" OnClick="ClickEventHandlingMethod"      runat="server" />
  3. Write the event handler. From the preceding line, you would need to write code like the following:

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




Called when the control is initialized. This is the first event called for every control.


Called when the Page object loads the control.


Called right before the control is rendered into the HTML result stream.


Called when the control is bound to a data source.


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.


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" />


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




The control's ID, which you can use to refer to the control in code.


The control's parent, which is usually the Page object.


If set to false, the control won't be displayed. Defaults to true.


Sets the ToolTip that's displayed when the user hovers the mouse pointer over the control. Not all browsers support this feature.


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



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


True if a CheckBox or RadioButton control is checked or 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020