CheckBoxes and RadioButtons

C# has two types of state buttons that can be in the on/off or true/false statesCheckBoxes and RadioButtons. Like class Button, classes CheckBox and RadioButton are derived from class ButtonBase.

CheckBoxes

A CheckBox is a small square that either is blank or contains a check mark. When the user clicks a CheckBox to select it, a check mark appears in the box. If the user clicks CheckBox again to deselect it, the check mark is removed. Any number of CheckBoxes can be selected at a time. A list of common CheckBox properties and events appears in Fig. 13.25.

Figure 13.25. CheckBox properties and events.

CheckBox properties and events

Description

Common Properties

Checked

Indicates whether the CheckBox is checked (contains a check mark) or unchecked (blank). This property returns a Boolean value.

CheckState

Indicates whether the CheckBox is checked or unchecked with a value from the CheckState enumeration (Checked, Unchecked or Indeterminate). Indeterminate is used when it is unclear whether the state should be Checked or Unchecked. For example, in Microsoft Word, when you select a paragraph that contains several character formats, then go to Format > Font, some of the CheckBoxes appear in the Indeterminate state. When CheckState is set to Indeterminate, the CheckBox is usually shaded.

Text

Specifies the text displayed to the right of the CheckBox.

Common Events

CheckedChanged

Generated when the Checked property changes. This is a CheckBox's default event. When a user double clicks the CheckBox control in design view, an empty event handler for this event is generated.

CheckStateChanged

Generated when the CheckState property changes.

The program in Fig. 13.26 allows the user to select CheckBoxes to change a Label's font style. The event handler for one CheckBox applies bold and the event handler for the other applies italic. If both CheckBoxes are selected, the font style is set to bold and italic. Initially, neither CheckBox is checked.

Figure 13.26. Using CheckBoxes to change font styles.

 1 // Fig. 13.26: CheckBoxTestForm.cs
 2 // Using CheckBoxes to toggle italic and bold styles.
 3 using System;
 4 using System.Drawing;
 5 using System.Windows.Forms;
 6
 7 // Form contains CheckBoxes to allow the user to modify sample text
 8 public partial class CheckBoxTestForm : Form
 9 {
10 // default constructor
11 public CheckBoxTestForm()
12 {
13 InitializeComponent();
14 } // end constructor
15
16 // toggle the font style between bold and 
17 // not bold based on the current setting 
18 private void boldCheckBox_CheckedChanged( 
19  object sender, EventArgs e ) 
20 { 
21  outputLabel.Font = 
22  new Font( outputLabel.Font.Name, outputLabel.Font.Size, 
23  outputLabel.Font.Style ^ FontStyle.Bold ); 
24 } // end metod boldCheckBox_CheckedChanged 
25
26 // toggle the font style between italic and 
27 // not italic based on the current setting 
28 private void italicCheckBox_CheckedChanged( 
29  object sender, EventArgs e ) 
30 { 
31  outputLabel.Font = 
32  new Font( outputLabel.Font.Name, outputLabel.Font.Size,
33  outputLabel.Font.Style ^ FontStyle.Italic ); 
34 } // end method italicCheckBox_CheckedChanged 
35 } // end class CheckBoxTestForm
 

The boldCheckBox has its Text property set to Bold. The italicCheckBox has its Text property set to Italic. The Text property of outputLabel is set to Watch the font style change. After creating the controls, we define their event handlers. Double clicking the CheckBoxes at design time creates empty CheckedChanged event handlers.

To change the font style on a Label, you must set its Font property to a new Font object (lines 2123 and 3133). The Font constructor that we use here takes the font name, size and style as arguments. The first two argumentsoutputLabel.Font.Name and outputLabel.Font.Sizeuse outputLabel's original font name and size. The style is specified with a member of the FontStyle enumeration, which contains Regular, Bold, Italic, Strikeout and Underline. (The Strikeout style displays text with a line through it.) A Font object's Style property is read-only, so it can be set only when the Font object is created.

Styles can be combined via bitwise operatorsoperators that perform manipulation on bits of information. Recall from Chapter 1 that all data is represented in the computer as combinations of 0s and 1s. Each 0 or 1 represents a bit. FontStyle has a System.FlagAttribute, meaning that the FontStyle bit values are selected in a way that allows us to combine different FontStyle elements to create compound styles, using bitwise operators. These styles are not mutually exclusive, so we can combine different styles and remove them without affecting the combination of previous FontStyle elements. We can combine these various font styles, using either the logical OR (|) operator or the logical exclusive OR (^) operator. When the logical OR operator is applied to two bits, if at least one bit of the two has the value 1, then the result is 1. Combining styles using the conditional OR operator works as follows. Assume that FontStyle.Bold is represented by bits 01 and that FontStyle.Italic is represented by bits 10. When we use the conditional OR (||) to combine the styles, we obtain the bits 11.

01 = Bold
10 = Italic
--
11 = Bold and Italic

The conditional OR operator helps create style combinations. However, what happens if we want to undo a style combination, as we did in Fig. 13.26?

The logical exclusive OR operator enables us to combine styles and to undo existing style settings. When logical exclusive OR is applied to two bits, if both bits have the same value, then the result is 0. If both bits are different, then the result is 1.

Combining styles using logical exclusive OR works as follows. Assume, again, that FontStyle.Bold is represented by bits 01 and that FontStyle.Italic is represented by bits 10. When we use logical exclusive OR (^) on both styles, we obtain the bits 11.

01 = Bold
10 = Italic
--
11 = Bold and Italic

Now, suppose that we would like to remove the FontStyle.Bold style from the previous combination of FontStyle.Bold and FontStyle.Italic. The easiest way to do so is to reapply the logical exclusive OR (^) operator to the compound style and FontStyle.Bold.

11 = Bold and Italic
01 = Bold
--
10 = Italic

This is a simple example. The advantages of using bitwise operators to combine FontStyle values become more evident when we consider that there are five different FontStyle values (Bold, Italic, Regular, Strikeout and Underline), resulting in 16 different FontStyle combinations. Using bitwise operators to combine font styles greatly reduces the amount of code required to check all possible font combinations.

In Fig. 13.26, we need to set the FontStyle so that the text appears in bold if it was not bold originally, and vice versa. Notice that line 23 uses the bitwise logical exclusive OR operator to do this. If outputLabel.Font.Style is bold, then the resulting style is not bold. If the text is originally italic, the resulting style is bold and italic, rather than just bold. The same applies for FontStyle.Italic in line 33.

If we did not use bitwise operators to compound FontStyle elements, we would have to test for the current style and change it accordingly. For example, in event handler boldCheckBox_CheckChanged, we could test for the regular style and make it bold; test for the bold style and make it regular; test for the italic style and make it bold italic; and test for the italic bold style and make it italic. This is cumbersome because, for every new style we add, we double the number of combinations. Adding a CheckBox for underline would require testing eight additional styles. Adding a CheckBox for strikeout would require testing 16 additional styles.

RadioButtons

Radio buttons (defined with class RadioButton) are similar to CheckBoxes in that they also have two statesselected and not selected (also called deselected). However, RadioButtons normally appear as a group, in which only one RadioButton can be selected at a time. Selecting one RadioButton in the group forces all the others to be deselected. Therefore, RadioButtons are used to represent a set of mutually exclusive options (i.e., a set in which multiple options cannot be selected at the same time).

Look and Feel Observation 13 7

Use RadioButtons when the user should choose only one option in a group.

Look and Feel Observation 13 8

Use CheckBoxes when the user should be able to choose multiple options in a group.

All RadioButtons added to a container become part of the same group. To separate RadioButtons into several groups, the RadioButtons must be added to GroupBoxes or Panels. The common properties and a common event of class RadioButton are listed in Fig. 13.27.

Figure 13.27. RadioButton properties and events.

RadioButton properties and events

Description

Common Properties

Checked

Indicates whether the RadioButton is checked.

Text

Specifies the RadioButton's text.

Common Event

CheckedChanged

Generated every time the RadioButton is checked or unchecked. When you double click a RadioButton control in design view, an empty event handler for this event is generated.

Software Engineering Observation 13 2

Forms, GroupBoxes, and Panels can act as logical groups for RadioButtons. The RadioButtons within each group are mutually exclusive to each other, but not to RadioButtons in different logical groups.

The program in Fig. 13.28 uses RadioButtons to enable users to select options for a MessageBox. After selecting the desired attributes, the user presses the Display Button to display the MessageBox. A Label in the lower-left corner shows the result of the MessageBox (i.e., which Button the user clickedYes, No, Cancel, etc.).

Figure 13.28. Using RadioButtons to set message-window options.

(This item is displayed on pages 623 - 626 in the print version)

 1 // Fig. 13.28: RadioButtonsTestForm.cs
 2 // Using RadioButtons to set message window options.
 3 using System;
 4 using System.Windows.Forms;
 5
 6 // Form contains several RadioButtons--user chooses one
 7 // from each group to create a custom MessageBox
 8 public partial class RadioButtonsTestForm : Form
 9 {
10 // create variables that store the user's choice of options
11 private MessageBoxIcon iconType;
12 private MessageBoxButtons buttonType;
13
14 // default constructor
15 public RadioButtonsTestForm()
16 {
17 InitializeComponent();
18 } // end constructor
19
20 // change Buttons based on option chosen by sender
21 private void buttonType_CheckedChanged( object sender, EventArgs e )
22 {
23 if ( sender == okButton ) // display OK Button
24 buttonType = MessageBoxButtons.OK;
25
26 // display OK and Cancel Buttons
27 else if ( sender == okCancelButton )
28 buttonType = MessageBoxButtons.OKCancel;
29
30 // display Abort, Retry and Ignore Buttons
31 else if ( sender == abortRetryIgnoreButton )
32 buttonType = MessageBoxButtons.AbortRetryIgnore;
33
34 // display Yes, No and Cancel Buttons
35 else if ( sender == yesNoCancelButton )
36 buttonType = MessageBoxButtons.YesNoCancel;
37
38 // display Yes and No Buttons
39 else if ( sender == yesNoButton )
40 buttonType = MessageBoxButtons.YesNo;
41
42 // only on option left--display Retry and Cancel Buttons
43 else
44 buttonType = MessageBoxButtons.RetryCancel;
45 } // end method buttonType_Changed
46
47 // change Icon based on option chosen by sender
48 private void iconType_CheckedChanged( object sender, EventArgs e )
49 {
50 if ( sender == asteriskButton ) // display asterisk Icon
51 iconType = MessageBoxIcon.Asterisk;
52
53 // display error Icon 54 else if ( sender == errorButton ) 55 iconType = MessageBoxIcon.Error; 56 57 // display exclamation point Icon 58 else if ( sender == exclamationButton ) 59 iconType = MessageBoxIcon.Exclamation; 60 61 // display hand Icon 62 else if ( sender == handButton ) 63 iconType = MessageBoxIcon.Hand; 64 65 // display information Icon 66 else if ( sender == informationButton ) 67 iconType = MessageBoxIcon.Information; 68 69 // display question mark Icon 70 else if ( sender == questionButton ) 71 iconType = MessageBoxIcon.Question; 72 73 // display stop Icon 74 else if ( sender == stopButton ) 75 iconType = MessageBoxIcon.Stop; 76 77 // only one option left--display warning Icon 78 else 79 iconType = MessageBoxIcon.Warning; 80 } // end method iconType_CheckChanged 81 82 // display MessageBox and Button user pressed 83 private void displayButton_Click( object sender, EventArgs e ) 84 { 85 // display MessageBox and store 86 // the value of the Button that was pressed 87 DialogResult result = MessageBox.Show( 88 "This is your Custom MessageBox.", "Custon MessageBox", 89 buttonType, iconType, 0, 0 ); 90 91 // check to see which Button was pressed in the MessageBox 92 // change text displayed accordingly 93 switch (result) 94 { 95 case DialogResult.OK: 96 displayLabel.Text = "OK was pressed."; 97 break; 98 case DialogResult.Cancel: 99 displayLabel.Text = "Cancel was pressed."; 100 break; 101 case DialogResult.Abort: 102 displayLabel.Text = "Abort was pressed."; 103 break; 104 case DialogResult.Retry: 105 displayLabel.Text = "Retry was pressed."; 106 break; 107 case DialogResult.Ignore: 108 displayLabel.Text = "Ignore was pressed."; 109 break; 110 case DialogResult.Yes: 111 displayLabel.Text = "Yes was pressed."; 112 break; 113 case DialogResult.No: 114 displayLabel.Text = "No was pressed."; 115 break; 116 } // end switch 117 } // end method displayButton_Click 118 } // end class RadioButtonsTestForm

(a)

(b)

(c) OKCancel button type

(d) OK button type

(e) AbortRetryIgnore button type

(f) YesNoCancel button type

(g) YesNo button type

(h) RetryCancel button type

To store the user's choices, we create and initialize the iconType and buttonType objects (lines 1112). Object iconType is of type MessageBoxIcon, and can have values Asterisk, Error, Exclamation, Hand, Information, None, Question, Stop and Warning. The sample output shows only Error, Exclamation, Information and Question icons.

Object buttonType is of type MessageBoxButtons, and can have values AbortRetryIgnore, OK, OKCancel, RetryCancel, YesNo and YesNoCancel. The name indicates the options that are presented to the user in the MessageBox. The sample output windows show MessageBoxes for all of the MessageBoxButtons enumeration values.

We created two GroupBoxes, one for each set of enumeration values. The GroupBox captions are Button Type and Icon. The GroupBoxes contain RadioButtons for the corresponding enumeration options, and the RadioButtons' Text properties are set appropriately. Because the RadioButtons are grouped, only one RadioButton can be selected from each GroupBox. There is also a Button (displayButton) labeled Display. When a user clicks this Button, a customized MessageBox is displayed. A Label (displayLabel) displays which Button the user pressed within the MessageBox.

The event handler for the RadioButtons handles the CheckedChanged event of each RadioButton. When a RadioButton contained in the Button Type GroupBox is checked, the checked RadioButton's corresponding event handler sets buttonType to the appropriate value. Lines 2145 contain the event handling for these RadioButtons. Similarly, when the user checks the RadioButtons belonging to the Icon GroupBox, the event handlers associated with these events (lines 4880) set iconType to its corresponding value.

The Click event handler for displayButton (lines 83117) creates a MessageBox (lines 8789). The MessageBox options are specified with the values stored in iconType and buttonType. When the user clicks one of the MessageBox's buttons, the result of the message box is returned to the application. This result is a value from the DialogResult enumeration that contains Abort, Cancel, Ignore, No, None, OK, Retry or Yes. The switch statement in lines 93116 tests for the result and sets displayLabel.Text appropriately.

PictureBoxes

Preface

Index

    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look

    Arrays

    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2

    Multithreading

    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures

    Generics

    Collections

    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types

    Index



    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Similar book on Amazon

    Flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net