Concepts of Programming Languages

(Sean Pound) #1

662 Chapter 14 Exception Handling and Event Handling


To register an event, a new EventHandler object must be created. The con-
structor for this class is sent the name of the handler method. The new object is
added to the predefined delegate for the event on the component object (using the
+= assignment operator). For example, when a radio button changes from unchecked
to checked, the CheckedChanged event is raised and the handlers registered on
the associated delegate, which is referenced by the name of the event, are called. If
the event handler is named rb_CheckedChanged, the following statement would
register the handler for the CheckedChanged event on the radio button plain:

plain. CheckedChanged +=
new EventHandler(rb_CheckedChanged);

Following is the RadioB example from Section 14.6 rewritten in C#. Once
again, because our focus is on event handling, we do not explain all of the
details of the program.

// RadioB.cs
// An example to illustrate event handling with
// interactive radio buttons that control the font
// style of a string of text

namespace RadioB {

using System;
using System.Drawing;
using System.Windows.Forms;

public class RadioB : Form {
private Label text = new Label();
private RadioButton plain = new RadioButton();
private RadioButton bold = new RadioButton();
private RadioButton italic = new RadioButton();
private RadioButton boldItalic = new RadioButton();

// Constructor for RadioB
public RadioB() {

// Init ialize the attributes of the text and radio
// buttons
text.AutoSize = true;
text.Text = "In what font style should I appear?";
plain.Location = new Point(220,0);
plain.Text = "Plain";
plain.Checked = true;
bold.Location = new Point(350, 0);
Free download pdf