Chapter 3
Controls for Windows
Forms
© 2004 Art Gittleman
Objectives
Add controls to • Make selections • Add links • Add images• Choose a date or number • Time events
• Make menu choices • Respond to dialogs
RadioButton
• May display text, an image, or both • Radio buttons from a group
user must select exactly one Example3-1 has three radio buttons Each represents a color
User selection changes Label text to the selected color
Drag radio buttons to form
Example3-1
Configure Properties
BackColor Red Font Bold True Text Red Anchor Top (Name) redButton
Configuring the Label
BorderStyle Fixed3D Font
Size 14
Text The text color is black TextAlign MiddleCenter
Anchor Left, Right Name display
The BorderStyle property
Used for the Label
None The default
FixedSingle Frames the label with black rectangle
Fixed3D Recesses the label
Handling a radio button click
private void redRadio_CheckedChanged (object sender, System.EventArgs e) {
display.ForeColor = Color.Red; display.Text = "The color is red"; }
Changes the foreground color and text of the label
The LinkLabel control
Lets us add links to web sites
This links to a site with information about George Washington
Handle a Link Click
Use the Start method of the Process class to start theInternet Explorer browser with the desired web site Event handling code:
private void presidentLink_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) {
System.Diagnostics.Process.Start(“IExplore”,
“http://www.whitehouse.gov/history/presidents/gw1.html”); }
Handle a Link Click
Use the Start method of the Process class to start the Internet Explorer browser with the desired web site
Event handling code:
private void presidentLink_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) {
System.Diagnostics.Process.Start(e.Link.LinkData.ToString( )); }
Add Radio Buttons to select
Handling a radio button selection
When the user selects a radio button we want to do three things
• Show the president’s name in the link • Underline the link
• Associate the link with the site containing the president’s biography.
The event handling code
private void george_CheckedChanged(object sender, System.EventArgs e) {
presidentLink.Text = "George Washington"; presidentLink.LinkBehavior = LinkBehavior.AlwaysUnderline; presidentLink.Links[0].LinkData = "http://www.whitehouse.gov/history/presidents/gw1.html"; }
A Collection Of Links
A LinkLabel may have a collection of links. The Links property holds that collection Links[0] refers to the first link in the
collection.
The LinkLabel in Example3-2 has only one link
The LinkData specifies the web site for the link
Grouping Radio Buttons
Drag a GroupBox to the Form
Add each RadioButton to the GroupBox GroupBox has a border with a title Change its Text property to
Choose a President
To change the title in the group box border A Form may have more than one group
Selecting a Style
The Border Style group box
Choose a border style for the link label The user chooses exactly one radio button
from each group – one to choose the president and one to choose the border style
Border Style event handling
private void singleBorder_CheckedChanged(object sender, System.EventArgs e) {
presidentLink.BorderStyle = BorderStyle.FixedSingle; }
private void threeDBorder_CheckedChanged (object sender, System.EventArgs e) {
presidentLink.BorderStyle = BorderStyle.Fixed3D; }
The PictureBox control
The SizeMode property
Normal Places the image in the upper-left corner, clipped if too large StretchImage Stretches or shrinks the image to fit AutoSize Resizes the PictureBox to the size of
the image
CenterImage Displays the image in the center if the PictureBox is larger than the image. Centers and clips the image if it is larger.
Size modes in Example3-3
Left AutoSize Right (top to bottom)
Normal CenterImage StretchImage Can set border styles too
None, FixedSingle, or Fixed3D
The CheckBox control
Make multiple selections Or select nothing
May have a label, an image, a background image
May appear with a box to check or like a button
Example3-4
Steps to add an image
• Click on the View, Properties menu item to show the list of properties.
• Click on the Image property to display a small button at the right.
• Click on the small button to pop up a window to open a file.
• Browse to locate the desired image and click the Openbutton.
Alignment
ImageAlign property -- place the image at different positions within a CheckBox. CheckAlign property functions in the same
way for the position of the box that the user checks.
TextAlign property determines the placement of the text
Steps to set alignment
• Click on the View, Properties menu item to show the list of properties.
• Click on the ImageAlign, CheckAlign, or TextAlign property to display a small button at the right.
• Click on the small button to pop up a grid of three rows and three columns that allows us to choose the alignment position.
• Click to choose one of the nine positions. The three vertical positions Top, Middle, and Bottom combine with the three horizontal positions, Left, Center, and Right to give the nine choices.
FlatStyle property for CheckBox
Flat The box appears flat
Popup Appears flat until the mouse passing over makes it appear three-dimensional
Standard Appears three-dimensional System Appearance determined by
the user’s operating system
Event-handling code
private void berryBox_CheckedChanged (object sender, System.EventArgs e) {
display.Text = "Strawberry " + berryBox.Checked;
}
Label shows the last box checked or unchecked
ListBox and ComboBox
ListBox shows all the elements ComboBox pops them up
Click on Items property to display a String Collection Editor to enter the items
SelectedItem property refers to the selected item
Example3-5
String Collection Editor
ListBox SelectionMode
None No items can be selected One One item can be selected MultiSimple Multiple items can be
selected MultiExtended Multiple items can be
selected and the user can use the shift, control, and arrow keys to make the selection
Selecting a list item
When the user selects an item, say hamburger
Program displays message in a label
hamburger has 9 letters
build this expression in four parts hamburger the selected item has
9 the length of the selected word letters
ListBox event handler
private void foodList_SelectedIndexChanged (object sender, System.EventArgs e) { display.Text = foodList.SelectedItem.ToString() + " has “ + foodList.SelectedItem.ToString().Length.ToString() + " letters"; }
ComboBox event handler
private void drinksCombo_SelectedIndexChanged (object sender, System.EventArgs e)
{
display.Text = "It's "
+ foodList.SelectedItem.ToString() + " and " + drinksCombo.Text; }
Display a message showing the food and drink selected
Keeping Track
Various controls help us keep track of dates, time, and numbers
DateTimePicker NumericUpDown StatusBar Timer
Example3-6
Example3-6 operation
DateTimePickerat top of form User chooses a date
NumericUpDownin the middle User selects a number
Buttonat bottom
User presses to display date in a label and number selected in another label
StatusBarat bottom shows current time
Timerupdates it every second, and changes label colors
DateTimePicker Format
Long Tuesday , January 28, 2003 Short 1/28/03
Time 10:32:56 AM
Button Click handling
private void showButton_Click
(object sender, System.EventArgs e) {
dateDisplay.Text = "Date selected: " + date.Value.ToLongDateString(); numberDisplay.Text = "Number selected "
+ number.Value.ToString(); }
A Timer control
Timer Tick event every second
private void timer1_Tick(object sender, System.EventArgs e) { currentDateTime.Text = DateTime.Now.ToString(); number.BackColor = dateDisplay.BackColor; dateDisplay.BackColor = numberDisplay.BackColor; numberDisplay.BackColor = number.BackColor; }
Copies time to status bar
Permutes background colors to give flashing effect
Menus
Drag a MainMenu control
Add a File menu
Add menu items
File menu
Open, Save, Print Format menu
Font, Color menu Foreground Background
Click on menu item – Event handler pops up a dialog
Open menu click event handler
private void openMenu_Click
(object sender, System.EventArgs e) {
openDialog.ShowDialog();
displayBox.LoadFile(openDialog.FileName, RichTextBoxStreamType.PlainText); }
Pops up a dialog to select the file Loads the selected file in a RichTextBox
Save Click event handler
private void saveMenu_Click
(object sender, System.EventArgs e) {
saveDialog.ShowDialog();
displayBox.SaveFile(saveDialog.FileName, RichTextBoxStreamType.PlainText); }
Pops up a dialog to enter a file name Saves file in RichTextBox using that name
Foreground Menu Click
private void foregroundMenu_Click (object sender, System.EventArgs e) {
colorDialog.ShowDialog();
displayBox.ForeColor =colorDialog.Color; }
Pops up a dialog to choose a color Changes the RichTextBox text color
Font Menu Click
private void fontMenu_Click
(object sender, System.EventArgs e) {
fontDialog.ShowDialog();
displayBox.Font = fontDialog.Font; }
Pops up a font dialog to choose a font Changes the font of the RichTextBox text