The RadioButton and CheckBox Controls


As mentioned earlier, the RadioButton and CheckBox controls share their base class with the Button control, although their appearance and use differs substantially from the button.

Radio buttons traditionally display themselves as a label with a dot to the left of it, which can be either selected or not. You should use the radio buttons when you want to give the user a choice between several mutually exclusive options, for example, if you want to ask for the user's gender.

To group radio boxes together so they create one logical unit you must use a GroupBox control. When you first place a GroupBox onto a form and then place the RadioButton controls you need within the borders of the GroupBox, the RadioButton controls will know to change their state to reflect that only one option within the group box can be selected. If you do not place the controls within a GroupBox, only one RadioButton on the form can be selected at any given time.

A CheckBox control traditionally displays itself as a label with, to the left, a small box with a check mark. You should use a check box when you want to allow users to choose one or more options. An example is a questionnaire asking which operating systems the user has tried (for example, Windows 2000, Windows XP, Linux, and so on).

You'll look at the important properties and events of these two controls, starting with the RadioButton, and then move on to a quick example of their use.

RadioButton Properties

Because the RadioButton control derives from ButtonBase and because you've already seen this in the example that used the button earlier, there are only a few properties to describe (shown in the following table). As always, should you need a complete list, please refer to the .NET Framework SDK documentation.

Name

Description

Appearance

A RadioButton can be displayed either as a label with a circular check to the left, middle, or right of it, or as a standard button. When it is displayed as a button, the control will appear depressed when selected and not depressed otherwise.

AutoCheck

When this property is true, a black point is displayed when the user clicks the radio button. When it is false the radio button must be manually checked in code from the Click event handler.

CheckAlign

By using this property, you can change the alignment of the check box portion of the radio button. The default is ContentAlignment.MiddleLeft.

Checked

This property indicates the status of the control. It is true if the control is displaying a black point or not, and false otherwise.

RadioButton Events

You will commonly only use one event when working with RadioButton controls, but as always there are many others that can be subscribed to. Only two are covered in this chapter (in the following table), and the only reason that the second event is mentioned is that there is a subtle difference between the two that should be noted.

Name

Description

CheckedChanged

This event is sent when the check of the RadioButton changes.

Click

This event is sent every time the RadioButton is clicked. This is not the same as the CheckedChange event, because clicking a RadioButton two or more times in succession only changes the Checked property once — and only if it wasn't checked already. Moreover, if the AutoCheck property of the button being clicked is false, the button will not be checked at all, and again only the Click event will be sent.

CheckBox Properties

As you would imagine, the properties and events of this control are very similar to those of the RadioButton, but the following table shows two new ones.

Name

Description

CheckState

Unlike the RadioButton, a CheckBox can have three states: Checked, Indeterminate, and Unchecked. When the state of the check box is Indeterminate, the control check next to the label is usually grayed, indicating that the current value of the check is not valid, for some reason cannot be determined (for example if the check indicates the read- only state of files, and two are selected, of which one is read-only and the other is not), or has no meaning under the current circumstances.

ThreeState

When this property is false, the user will not be able to change the CheckState state to Indeterminate. You can, however, still change the CheckState property to Indeterminate from code.

CheckBox Events

You will normally use only one or two events on this control. Note that, even though the CheckChanged event exists on both the RadioButton and the CheckBox controls, the effects of the events differ. The following table shows the CheckBox events.

This concludes the events and properties of the RadioButton and CheckBox controls. But before looking at an example using these, let's take a look at the GroupBox control, which was mentioned earlier.

Name

Description

CheckedChanged

Occurs whenever the Checked property of the check box changes. Note that in a CheckBox where the ThreeState property is true, it is possible to click the check box without changing the Checked property. This happens when the check box changes from checked to indeterminate state.

CheckStateChanged

Occurs whenever the CheckedState property changes. As Checked and Unchecked are both possible values of the CheckedState property, this event will be sent whenever the Checked property changes. In addition to that, it will also be sent when the state changes from Checked to Indeterminate.

The GroupBox Control

The GroupBox control is often used to logically group a set of controls such as the RadioButton and CheckBox, and provide a caption and a frame around this set.

Using the group box is as simple as dragging it onto a form, and then dragging the controls it should contain onto it (but not the other way round — you can't lay a group box over some preexisting controls). The effect of this is that the parent of the controls becomes the group box, rather than the form, and it is, therefore, possible to have more than one RadioButton selected at any given time. Within the group box, however, only one RadioButton can be selected.

The relationship between parent and child probably needs to be explained a bit more. When a control is placed on a form, the form is said to become the parent of the control, and hence the control is the child of the form. When you place a GroupBox on a form, it becomes a child of a form. Because a group box can itself contain controls, it becomes the parent of these controls. The effect of this is that moving the GroupBox will move all of the controls placed on it.

Another effect of placing controls on a group box is that it allows you to affect the contained controls by setting the corresponding property on the group box. For instance, if you want to disable all the controls within a group box, you can simply set the Enabled property of the GroupBox to false.

The GroupBox control is demonstrated in the following Try It Out.

Try It Out – RadioButton and CheckBox Example

image from book

You'll modify the TextBoxTest example you created earlier with the demonstration of text boxes. In that example, the only possible occupation was Programmer. Instead of forcing users to type this out in full, you change this text box to a check box.

To demonstrate the RadioButton, you ask the user to provide one more piece of information: his or her gender.

Change the text box example like this:

  1. Remove the label named labelOccupation and the text box named textBoxOccupation.

  2. Add a CheckBox, a GroupBox and two RadioButton controls, and name the new controls as shown in Figure 14-12. Notice that the GroupBox control is located on the Containers tab in the Toolbox panel.

    image from book
    Figure 14-12

  3. The Text property of the RadioButton and CheckBox controls should be the same as the names of the controls without the first three letters, and for the GroupBox the Text property should be Sex.

  4. Set the Checked property of the checkBoxProgrammer check box to true.

  5. Set the Checked property of either radioButtonMale or radioButtonFemale to true. Note that you cannot set both to true. If you try to do this with a second button, the value of the first RadioButton is automatically changed to false.

No more needs to be done on the visual part of the example, but there are a number of changes in the code. First, you need to remove all the references to the text box that you've removed. Go to the code and complete the following steps.

  1. In the constructor of the form, remove the three lines that refer to textBoxOccupation. This includes subscriptions to the Validating and TextChanged events and the line that sets the Tag property to false.

  2. Remove the txtOccupation_Validating() method entirely.

How It Works

The txtBox_TextChanged method included tests to see if the calling control was the textBoxOccupation TextBox. You now know for sure that it will not be (since you removed it), and so you change the method by removing the else if block and modify the if test as follows:

private void textBox_TextChanged(object sender, System.EventArgs e) {    // Cast the sender object to a Textbox.    TextBox tb = (TextBox)sender;        // Test if the data is valid and set the     // color accordingly. if (tb.Text.Length == 0) { tb.Tag = false; tb.BackColor = Color.Red; } else    {       tb.Tag = true;       tb.BackColor = SystemColors.Window;    }        // Call ValidateOK to set the OK button.    ValidateOK(); }

Another place in which you check the value of the text box you've removed is in the ValidateOK() method. Remove the check entirely so the code becomes:

private void ValidateOK() {    // Set the OK button to enabled if all the Tags are true. this.buttonOK.Enabled = ((bool)(this.textBoxAddress.Tag) && (bool)(this.textBoxAge.Tag) && (bool)(this.textBoxName.Tag)); }

Since you are using a check box rather than a text box, you know that the user cannot enter any invalid information, because he or she will always be either a programmer or not.

You also know that the user is either male or female, and because you set the property of one of the RadioButtons to true, the user is prevented from choosing an invalid value. Therefore, the only thing left to do is change the help text and the output. You do this in the button event handlers:

private void buttonHelp_Click(object sender, System.EventArgs e) {    // Write a short description of each TextBox in the Output TextBox.    string output;        output = "Name = Your name\r\n";    output += "Address = Your address\r\n"; output += "Programmer = Check 'Programmer' output += "Sex = Choose your sex\r\n";    output += "Age = Your age";        // Insert the new text.    this.textBoxOutput.Text = output; }

Only the help text is changed, so there is nothing surprising in the help method. It gets slightly more interesting in the OK method:

private void buttonOK_Click(object sender, EventArgs e) {   // No testing for invalid values is done, as that should   // not be necessary.       string output;       // Concatenate the text values of the four TextBoxes.   output = "Name: " + this.textBoxName.Text + "\r\n";   output += "Address: " + this.textBoxAddress.Text + "\r\n"; output += "Occupation: " + (string)(this.checkBoxProgrammer.Checked ? "Programmer" : "Not a programmer") + "\r\n"; output += "Sex: " + (string)(this.radioButtonFemale.Checked ? "Female" : "Male") + "\r\n";   output += "Age: " + this.textBoxAge.Text;       // Insert the new text.   this.textBoxOutput.Text = output; }

The first of the highlighted lines is the line in which the user's occupation is printed. You investigate the Checked property of the CheckBox, and if it is true, you write the string Programmer. If it is false, you write Not a programmer.

The second line examines only the radio button rdoFemale. If the Checked property is true on that control, you know that the user claims to be female. If it is false you know that the user claims to be male. It is possible to have radio buttons without any of them being checked when you start the program — but because you checked one of the radio buttons at design time, you know for sure that one of the two radio buttons will always be checked.

When you run the example now, you should get a result similar to that shown in Figure 14-13.

image from book
Figure 14-13

image from book




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

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