Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

7.2 Button Classes, Group Box, Panel, and Label

The Button Class

A button is the most popular way to enable a user to initiate some program action. Typically, the button responds to a mouse click or keystroke by firing a Click event that is handled by an event handler method that implements the desired response.

constructor: public Button()

The constructor creates a button instance with no label. The button’s Text property sets its caption and can be used to define an access key (see Handling Button Events section); its Image property is used to place an image on the button’s background.

Setting a Button’s Appearance

Button styles in .NET are limited to placing text and an image on a button, making it flat or three-dimensional, and setting the background/foreground color to any available color. The following properties are used to define the appearance of buttons, check boxes, and radio buttons:

FlatStyle

This can take four values: FlatStyle.Flat, FlatStyle.Popup, FlatStyle.Standard, and FlatStyle.System. Standard is the usual three-dimensional button. Flat creates a flat button. Popup creates a flat button that becomes three-dimensional on a mouseover. System results in a button drawn to suit the style of the operating system.

Image

Specifies the image to be placed on the button. The Image.FromFile method is used to create the image object from a specified file:

button1.Image = Image.FromFile("c:\\book.gif");

ImageAlign

Specifies the position of the image on the button. It is set to a value of the ContentAlignment enum:

button1.ImageAlign = ContentAlignment.MiddleRight;

TextAlign

Specifies the position of text on the image using the ContentAlignment value.

Handling Button Events

A button’s Click event can be triggered in several ways: by a mouse click of the button, by pressing the Enter key or space bar, or by pressing the Alt key in combination with an access key. An access key is created by placing an & in front of one of the characters in the control’s Text property value.

The following code segment declares a button, sets its access key to C, and registers an event handler to be called when the Click event is triggered:

Button btnClose = new Button();
btnClose.Text= "&Close"; // Pushing ALT + C triggers event
btnClose.Click += new EventHandler(btnClose_Clicked);
// Handle Mouse Click, ENTER key, or Space Bar 
private void btnClose_Clicked(object sender, System.EventArgs e)
{ this.Close(); }

Note that a button’s Click event can also occur in cases when the button does not have focus. The AcceptButton and CancelButton form properties can specify a button whose Click event is triggered by pushing the Enter or Esc keys, respectively.

The CheckBox Class

The CheckBox control allows a user to select a combination of options on a form—in contrast to the RadioButton, which allows only one selection from a group.

constructor: public CheckBox()

The constructor creates an unchecked check box with no label. The Text and Image properties allow the placement of an optional text description or image beside the box.

Setting a CheckBox’s Appearance

Check boxes can be displayed in two styles: as a traditional check box followed by text (or an image) or as a toggle button that is raised when unchecked and flat when checked. The appearance is selected by setting the Appearance property to Appearance.Normal or Appearance.Button. The following code creates the two check boxes shown in Figure 7-2.

// Create traditional check box
this.checkBox1 = new CheckBox();
this.checkBox1.Location = 
    new System.Drawing.Point(10,120);
this.checkBox1.Text = "La Traviata";
this.checkBox1.Checked = true;
// Create Button style check box
this.checkBox2 = new CheckBox();
this.checkBox2.Location = 
    new System.Drawing.Point(10,150);
this.checkBox2.Text = "Parsifal";
this.checkBox2.Appearance = Appearance.Button;
this.checkBox2.Checked = true;
this.checkBox2.TextAlign = ContentAlignment.MiddleCenter;
Figure 7-2

Figure 7-2 CheckBox styles

The RadioButton Class

The RadioButton is a selection control that functions the same as a check box except that only one radio button within a group can be selected. A group consists of multiple controls located within the same immediate container.

constructor: public RadioButton()

The constructor creates an unchecked RadioButton with no associated text. The Text and Image properties allow the placement of an optional text description or image beside the box. A radio button’s appearance is defined by the same properties used with the check box and button: Appearance and FlatStyle.

Placing Radio Buttons in a Group

Radio buttons are placed in groups that allow only one item in the group to be selected. For example, a 10-question multiple choice form would require 10 groups of radio buttons. Aside from the functional need, groups also provide an opportunity to create an aesthetically appealing layout.

The frequently used GroupBox and Panel container controls support background images and styles that can enhance a form’s appearance. Figure 7-3 shows the striking effect (even more so in color) that can be achieved by placing radio buttons on top of a GroupBox that has a background image.

Figure 7-3

Figure 7-3 Radio buttons in a GroupBox that has a background image

Listing 7-1 presents a sample of the code that is used to place the radio buttons on the GroupBox control and make them transparent so as to reveal the background image.

Listing 7-1 Placing Radio Buttons in a GroupBox

using System.Drawing;  
using System.Windows.Forms;
public class OperaForm : Form
{
  private RadioButton radioButton1;
  private RadioButton radioButton2;
  private RadioButton radioButton3;
  private GroupBox groupBox1;
  public OperaForm()
  {
   this.groupBox1 = new GroupBox();
   this.radioButton3 = new RadioButton();
   this.radioButton2 = new RadioButton();
   this.radioButton1 = new RadioButton();
   // All three radio buttons are created like this
   // For brevity only code for one button is included
   this.radioButton3.BackColor = Color.Transparent;
   this.radioButton3.Font = new Font("Microsoft Sans Serif",
                    8.25F, FontStyle.Bold);
   this.radioButton3.ForeColor = 
      SystemColors.ActiveCaptionText;
   this.radioButton3.Location = new Point(16, 80);
   this.radioButton3.Name = "radioButton3";
   this.radioButton3.Text = "Parsifal";
   // Group Box
   this.groupBox1 = new GroupBox();
   this.groupBox1.BackgroundImage = 
      Image.FromFile("C:\\opera.jpg");
   this.groupBox1.Size = new Size(120, 112);
   // Add radio buttons to groupbox
   groupBox1.Add( new Control[]{radioButton1,radiobutton2,
                  radioButton3});
  }
}

Note that the BackColor property of the radio button is set to Color.Transparent. This allows the background image of groupBox1 to be displayed. By default, BackColor is an ambient property, which means that it takes the color of its parent control. If no color is assigned to the radio button, it takes the BackColor of groupBox1 and hides the image.

The GroupBox Class

A GroupBox is a container control that places a border around its collection of controls. As demonstrated in the preceding example, it is often used to group radio buttons; but it is also a convenient way to organize and manage any related controls on a form. For example, setting the Enabled property of a group box to false disables all controls in the group box.

constructor: public GroupBox()

The constructor creates an untitled GroupBox having a default width of 200 pixels and a default height of 100 pixels.

The Panel Class

The Panel control is a container used to group a collection of controls. It’s closely related to the GroupBox control, but as a descendent of the ScrollableControl class, it adds a scrolling capability.

constructor: public Panel()

Its single constructor creates a borderless container area that has scrolling disabled. By default, a Panel takes the background color of its container, which makes it invisible on a form.

Because the GroupBox and Panel serve the same purpose, the programmer is often faced with the choice of which to use. Here are the factors to consider in selecting one:

  • A GroupBox may have a visible caption, whereas the Panel does not.
  • A GroupBox always displays a border; a Panel’s border is determined by its BorderStyle property. It may be set to BorderStyle.None, BorderStyle.Single, or BorderStyle.Fixed3D.
  • A GroupBox does not support scrolling; a Panel enables automatic scrolling when its AutoScroll property is set to true.

A Panel offers no features to assist in positioning or aligning the controls it contains. For this reason, it is best used when the control layout is known at design time. But this is not always possible. Many applications populate a form with controls based on criteria known only at runtime. To support the dynamic creation of controls, .NET offers two layout containers that inherit from Panel and automatically position controls within the container: the FlowLayoutPanel and the TableLayoutPanel.

The FlowLayoutPanel Control

Figure 7-4 shows the layout of controls using a FlowLayoutPanel.

Figure 7-4

Figure 7-4 FlowLayoutPanel

This "no-frills" control has a single parameterless constructor and two properties worth noting: a FlowDirection property that specifies the direction in which controls are to be added to the container, and a WrapControls property that indicates whether child controls are rendered on another row or truncated.

The following code creates a FlowLayoutPanel and adds controls to its collection:

FlowLayoutPanel flp = new FlowLayoutPanel();
flp.FlowDirection = FlowDirection.LefttoRight;
// Controls are automatically positioned left to right
flp.Controls.Add(Button1);
flp.Controls.Add(Button2);
flp.Controls.Add(TextBox1);
flp.Controls.Add(Button3);
this.Controls.Add(flp);   // Add container to form

The FlowDirection enumerator members are BottomUp, LeftToRight, RighttoLeft, and TopDown. LefttoRight is the default.

TableLayoutPanel Control

Figure 7-5 shows the grid layout that results from using a TableLayoutPanel container.

Figure 7-5

Figure 7-5 TableLayoutPanel organizes controls in a grid

This code segment creates a TableLayoutPanel and adds the same four controls used in the previous example. Container properties are set to define a layout grid that has two rows, two columns, and uses an Inset border style around each cell. Controls are always added to the container moving left-to-right, top-to-bottom.

TableLayoutPanel tlp = new TableLayoutPanel();
// Causes the inset around each cell
tlp.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset;
tlp.ColumnCount = 2;   // Grid has two columns
tlp.RowCount  = 2;   // Grid has two rows
// If grid is full add extra cells by adding column
tlp.GrowStyle = TableLayoutPanelGrowStyle.AddColumns;
// Padding (pixels)within each cell (left, top, right, bottom)
tlp.Padding = new Padding(1,1,4,5); 
tlp.Controls.Add(Button1);
tlp.Controls.Add(Button2);
// Other controls added here

The GrowStyle property is worth noting. It specifies how controls are added to the container when all of its rows and columns are filled. In this example, AddColumns specifies that a column be added to accommodate new controls. The other options are AddRows and None; the latter causes an exception to be thrown if an attempt is made to add a control when the panel is filled.

The Label Class

The Label class is used to add descriptive information to a form.

constructor: public Label()

The constructor creates an instance of a label having no caption. Use the Text property to assign a value to the label. The Image, BorderStyle, and TextAlign properties can be used to define and embellish the label’s appearance.

Figure 7-6

Figure 7-6 Label containing an image and text

The following code creates the label shown in Figure 7-6:

Label imgLabel = new Label();
imgLabel.BackColor= Color.White; 
Image img = Image.FromFile("c:\\rembrandt.jpg");
imgLabel.Image= img;
imgLabel.ImageAlign= ContentAlignment.TopCenter;
imgLabel.Text="Rembrandt";
imgLabel.TextAlign= ContentAlignment.BottomCenter;
imgLabel.BorderStyle= BorderStyle.Fixed3D;
imgLabel.Size = new Size(img.Width+10, img.Height+25);

One of its less familiar properties is UseMnemonic. By setting it to true and placing a mnemonic (& followed by a character) in the label’s text, you can create an access key. For example, if a label has a value of &Sum, pressing Alt-S shifts the focus to the control (based on tab order) following the label.

  • + Share This
  • 🔖 Save To Your Account

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.

Overview


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.

Surveys

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.

Newsletters

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.

Security


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

Children


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

Marketing


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.

Choice/Opt-out


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.

Links


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