- 7.1 A Survey of .NET Windows Forms Controls
- 7.2 Button Classes, Group Box, Panel, and Label
- 7.3 PictureBox and TextBox Controls
- 7.4 ListBox, CheckedListBox, and ComboBox Classes
- 7.5 The ListView and TreeView Classes
- 7.6 The ProgressBar, Timer, and StatusStrip Classes
- 7.7 Building Custom Controls
- 7.8 Using Drag and Drop with Controls
- 7.9 Using Resources
- 7.10 Summary
- 7.11 Test Your Understanding
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 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 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 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 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 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.