Sie sind auf Seite 1von 44

Chapter 2

Using Built-in Control Classes

Fundamental Object Oriented Programming


School of Engineering
Ngee Ann Polytechnic
Objectives
 Use the following controls:
 labels,
 buttons,
 textboxes,
 group boxes,
 check boxes,
 radio buttons,
 list boxes,
 combo boxes and
 picture boxes.
 Set the properties of controls during design and run time.
 Define access keys.
 Select an accept and a cancel button.
 Reset the focus during run time.

2015 Oct 6FOOP Slide 2-2


Introduction
 User interface must be clear and consistent.
 We need to create an easy-to-use User Interface (UI)
that is intuitive!
 This can be done using controls such as text
boxes, radio buttons, check boxes, combo boxes
etc. for input/output interface.

2015 Oct 6FOOP Slide 2-3


Control Objects
 User interface for Windows Form applications are designed
using controls like Text box, Labels, Buttons, Radio buttons,
CheckBox, ComboBox and ListBox.
 Controls are programming construct that has its own set of
properties, methods, and events that make it suitable for
a particular purpose.
 You can manipulate controls in the designer during design
time or write codes to dynamically manipulate controls at
run time.

What you called ‘function’ in compro is known as ‘method’ in C#!

2015 Oct 6FOOP Slide 2-4


Control Objects …. cont
 Properties are appearance of a control
 E.g BackColor, Size, Font and Text of a Label

 Methods are actions that can be performed by a control


 E.g Hide(), Show() and Clear() of a Textbox.

 Events are occurrences that the control respond to.


 E.g. MouseClick, KeyPress and TextChanged of a Textbox.

 When an event occur the codes in the event handler will


automatically by executed.

 E.g of a button click event handler


private void displayButton_Click (object sender, EventArgs e)
{
//code will execute whenever the button is click
}

2015 Oct 6FOOP Slide 2-5


Controls – Naming Convention
How to name your control?
1. Start with a lowercase non-digit character.
2. Capitalize each subsequence word describing the
purpose of control. Follow by the type of the control.
3. No spaces or symbols like ?,/,&, etc.
4. Names cannot be C# reserve word like string, int, float.

E.g. messageLabel Question:


studentNameTextBox What is wrong with these
names?
mediumSizeRadioButton
1 3greenLabel
extraMilkAndSugarCheckBox 2 first ClassTextBox
3 d.Label
4 double

2015 Oct 6FOOP Slide 2-6


Label Control
To display texts or images that cannot be edited by the user.
Not meant for user input.

 Text property
 determines what is displayed on the label

 can be set at design time in properties window

 or set during run time using program code


messageLabel.Text = “Set Meal for $5 only”;
messageLabel.Text = “”; // clear the label

2015 Oct 6FOOP Slide 2-7


Label Control….cont
Single line
border
 BorderStyle property
 determines if the label has a visible border.
 Usually set at design time
 Visible property
 Determines whether a label visible or not:
E.g. messageLabel.Visible = true;

Question: What is wrong with these statements? Make


1. messageLabel = Good Morning!; visible

2. messageLabel.Visible

2015 Oct 6FOOP Slide 2-8


Label Control….cont
 Fixed string or string literal is enclosed in double quotes
 “How are you?”, “Here is $10.00”, “47Kg”, “Au Revoir!”
 String literal must be in one line.
 To break a string literal into two lines, use the escape sequence
\n. E.g. “Goodbye!\nPlease come again!” will be displayed as
Goodbye!
Please come again!

Question: What will the label, msgLabel display?


1. msgLabel.Text = “Dear sir, \nHow are you?”;

Question: How many errors are there in this statement?


1. msgLabel = “Dear sir,
How are you?”;

2015 Oct 6FOOP Slide 2-9


TextBox Control
To get input from the user or to display text.

qtyTextBox

Text property
 The current text being displayed or to be displayed.
 To copy a TextBox to a Label.
outputLabel.Text = qtyTextBox.Text;
 To display a text on the textBox
qtyTextBox = “1”;

2015 Oct 6FOOP Slide 2-10


TextBox Control ….cont
 Any string or text can be joined using the plus “+” sign.
E.g.
 msgLabel.text = “Hello, ” + “how are you?” ;
will display “Hello, how are you?”
 msgLabel.text = “You have ordered ” + qtyTextBox.Text + “set
meal.”;
will display “You have ordered 1 set meal.” If qtyTextBox is 1.

Question: What will the label, msgLabel display?


1. msgLabel.text = “Welcome! ” + nameTextBox.Text;

2. msgLabel.text = “Welcome! ” + “nameTextBox.Text”;

2015 Oct 6FOOP Slide 2-11


TextBox Control ….cont
 TextAlign property
 aligns text to the left, right or center.
 Numeric text is aligned to the right as in a calculator.
 Usually set at design time in properties window
 ForeColor property
 sets the colour of the text
 Sets at design time or runtime
messageTextBox.ForeColor = Color.Red;
 BackColor property
 sets the colour of textbox back ground
 Sets at design time or runtime
messageTextBox.BackColor = Color.White;

2015 Oct 6FOOP Slide 2-12


TextBox Control ….cont

 Clear() method
 Ability to clear itself.
Eg: qtyTextBox.Clear();
 TextBox can also be cleared as shown:
qtyTextBox.Text = “”;

 Focus() method
 Ability to set the cursor to itself, to receive input from keyboard.
Eg: qtyTextBox.Focus();
 Focus can be moved to next control by the TAB key.
Has focus
No focus

2015 Oct 6FOOP Slide 2-13


TextBox Control ….cont
Question: What is wrong with these statements?
1. messageTextBox.Clear() = “”;
2. messageTextBox.SetFocus();
3. messageTextBox = “Please wait”;

Question (by program):


1) How to copy the content of nameTextBox to messageLabel?

2) How to Copy the content of messageLabel to nameTextBox?

2015 Oct 6FOOP Slide 2-14


CheckBox Control
Allow user to select multiple options.

Checked property Text property

 Text property
 To display the caption of the CheckBox.
 Usually set at design time.
 Checked property
 To indicate if the option is selected.
 May set as a default, at design time.
 Toggles when user clicks

2015 Oct 6FOOP Slide 2-15


CheckBox Control….cont
 Checked property
 To select the option by program:
englishCheckBox.Checked = true;

 To unselect the option by program:


malayCheckBox.Checked = false;

 When a user clicks on a CheckBox, its Checked property


toggles and CheckedChanged event is triggered

Question: What is wrong in selecting the CheckBox?


1. malayCheckBox.Checked;

2. malayCheckBox.Checked() = “false”;

2015 Oct 6FOOP Slide 2-16


Check Boxes ….cont
 CheckedChanged event
 Is triggered whenever the checked property is changed
either by mouse click or by program.
 Codes in the CheckedChanged event handler is
automatically executed.
 An if-else statement is used to check the Checked property
and carry out the appropriate action.
private void visibleCheckBox_CheckedChanged (……)
{ if (englishCheckBox.Checked) {
// if selected
}
else {
// if not selected
}
}

2015 Oct 6FOOP Slide 2-17


Check Boxes ….cont
 CheckedChanged event
 whenever the checked property is changed the
CheckedChanged event handler is automatically executed.
 Do not change the checked property inside its
CheckedChanged event or it will trigger itself again.

Question: what is wrong with this program?


private void visibleCheckBox_CheckedChanged (……)
{ If (visibleCheckBox.checked)
visibleCheckBox.checked = false;
else
visibleCheckBox.checked = true;
}

2015 Oct 6FOOP Slide 2-18


GroupBox Control
 To group related controls together!

Text property of GroupBox

GroupBox

 Text property (of GroupBox)


 The title or caption of the group box
 Usually set at design time.

2015 Oct 6FOOP Slide 2-19


RadioButton Control
Allow user to select only one option in the group.

Text property

Checked property

 Text property
 The caption of the RadioButton.
 Checked property
 To indicate if the option is selected.
 May set as a default at design time.

2015 Oct 6FOOP Slide 2-20


RadioButton Control….cont
 Checked property
 To select the option by program:
blueRadioButton.Checked = true;

 To unselect the option by program:


blackRadioButton.Checked = false;

 When a user clicks on a RadioButton, its Checked property


becomes true. Only one Radiobutton’s Checked property
can be true at anytime. Any other Checked property that is
previously true automatically become false.

Slide 2-21
2015 Oct 6FOOP
Radio Buttons ….cont

 CheckedChanged event
 Is triggered whenever the checked property is
changed either by mouse click or by program.
 Codes in the CheckedChanged event handler is
automatically executed.

Question: when the option


selected changes from Blue to
Black, how many
CheckedChanged events are
triggered?

2015 Oct 6FOOP Slide 2-22


PictureBox Control
To display graphics in bitmap, GIF, JPEG, metafile, or icon
format.

 Image property
 The graphic to be displayed.
 Set using Properties window.
 Or during run time, using Fromfile method eg:
logoPictureBox.Image =
Image.FromFile(“C:\\Graphics\\logo.bmp”); Note: double “\”

2015 Oct 6FOOP Slide 2-23


PictureBox Control ….cont
 SizeMode property
 Resize the image in 3 modes
 StretchImage: picture resizes to fill the control

 Autosize: control resizes to fit picture

 Normal: no resizing of picture or control. Picture is

clipped if it is too big.

 Visible property
 to hide the picture box or show it.
 Set using Properties window or program.
E.g. bluePictureBox.Visible = false;

2015 Oct 6FOOP Slide 2-24


Buttons Control..cont
For user to click it to initiate an action.

Text property

 Text property
 The caption of the Button.
 Set using the Properties window or in program.
E.g. enterButton.Text = “&Enter”;
 Click event
 When a user clicks a button, the Click event is invoked.

Slide 2-25
2015 Oct 6FOOP
Buttons Control..cont
Question: What does the button click event do?
private void onOffButton_Click(object sender, EventArgs e)
{ if (onOffButton.Text == “&ON”)
onOffButton.Text = “&OFF”;
else
onOffButton.Text = “&ON”;
//changing text does not cause a click event
}

Question: What is wrong with the statements below?


1. if (greenRadioButton == Checked)
2. greenRadioButton.Checked = “True”;
3. greenRadioButton = true;

Slide 2-26
2015 Oct 6FOOP
Access Keys
An access key is an underlined character in the text of a
button. A button "click" can be simulated by pressing the
ALT key + access key
 An ampersand (&) before a letter in the Text property of
a button to create an access key
 Set using Properties window
E.g. &OK (access key o: Alt + o)
E&xit (access key x: Alt + x)
 Set by program.
E.g. exitButton.text = “E&xit”;

2015 Oct 6FOOP Slide 2-27


AcceptButton of a Form
On a Windows Form, a button can be designated as the
AcceptButton. Pressing the ENTER key is equivalent
to the AcceptButton being clicked.
 AcceptButton property

 Property of a Windows Form.


 To designate a button as the
AcceptButton .
Select a Button
to be the
AcceptButton

2015 Oct 6FOOP Slide 2-28


CancelButton of a Form
On a Windows Form, a button can be designated as the
CancelButton. Pressing the ESC key is equivalent
to the CancelButton being clicked.
 CancelButton property

 Property of a Windows Form.


 To designate a button as the
CancelButton .

Select a Button
to be the
CancelButton

Slide 2-29
2015 Oct 6FOOP
ListBox and Combo Control
 To display a list of items for user to make a selection.
 Different between listBox and comboBox:
 ComboBox has Dropdown style property.

Combo Box

List Box

2015 Oct 6FOOP Slide 2-30


ListBox and Combo Control….cont
 List items can be added during
 design time: Items property in properties window.
 Run time: using Items.Add(ItemValue) or
Items.Insert(IndexPosition, ItemValue)
 orderListBox.Items.Add(qtyTextBox.Text);
 priceComboBox.Items.Add(“$5.00”);
 sizeComboBox.Items.Insert(1,”medium”);
 Index position for the first item is 0.
 Items can be sorted alphabetically by setting the
Sorted property to true.

2015 Oct 6FOOP Slide 2-31


ListBox and Combo Control….cont

 Items can be removed using


 Items.Remove(ItemValue)
 msgListBox.Items.Remove(“Hello”);
 priceComboBox.Items.Remove(priceTextBox.Text);
 Items.RemoveAt(IndexPosition)
 sizeComboBox.Items.RemoveAt(0);
 orderListBox.Items.RemoveAt(orderListBox.SelectedIndex)
 List can be cleared using
 Items.Clear()
 orderListBox.Items.Clear();

2015 Oct 6FOOP Slide 2-32


ListBox and Combo Control….cont
 Question:
 1) Add the text from nameTextBox to nameComboBox?

 2) Delete the first item in the priceListBox?

 3) Delete an item in the orderListBox that is equal to


choiceComboBox.Text.

2015 Oct 6FOOP Slide 2-33


ListBox and Combo Control….cont
 The number of items in the list can be determined
using Items.Count property.
 msgLabel.Text = “number of items in the list is: “ +
nameComboBox.Items.Count.ToString();
 An item in the list can be selected using
Object.Items[IndexPosition] and IndexPosition can
be obtained from SelectedIndex property.
 titleLabel.Text =
titleComboBox.Items[titleComboBox.SelectedIndex];
 priceListBox.Items[5] = “$10”;

2015 Oct 6FOOP Slide 2-34


ComboBox
 The ComboBox control combines TextBox features with
a drop-down list – a GUI component that contains a list
from which a value can be selected. It usually appears
as a TextBox with a down arrow to its right:

 By default, the user can enter text into the TextBox or


click the down arrow to display a list of predefined items.
If a user chooses an element from this list, that element
is displayed in the TexBox. If the list contains more
elements than can be displayed in the drop-down list, a
scrollbar appears.

2015 Oct 6FOOP Slide 2-35


3 DropDownStyle of ComboBox:

2015 Oct 6FOOP Slide 2-36


ComboBox
Properties

That maximum
number of items that
a drop-down list can
display at one time
is set by property
MaxDropDownItems
.

2015 Oct 6FOOP Slide 2-37


Common Properties
ComboBox DropDownStyle Determines the display style of the ComboBox:
Properties, Value Simple means that the text portion is editable, and the list portion is
events & always visible.
methods Value DropDown (the default) means that the text portion is editable, but
the user must click the arrow button to see the list portion.
Value DropDownList means that the text portion is not editable, and the
user must click the arrow button to see the list portion.
Items The collection of items in the ComboBox control
Items.Count The number of items in the ComboBox
MaxDropDownItems Specifies the maximum number of items (between 1 and 100) that the drop-
down list can display. If the number of items exceeds the maximum number
of items to display, a scrollbar appears.
SelectedIndex Returns the index of the selected items. If nothing is selected, -1 is returned.
SelectedItems Returns a reference to the selected item
Sorted Indicates whether items are sorted alphabetically. Setting this property’s
value to true sorts the items. The default is false.

Common Event
SelectedIndexChanged Generated when the selected index changes (such as when a different item
is selected). This is the default event when control is double clicked in the
designer.

Methods
Add method Use to add item into the list.
Example:comboBox1.Items.Add(“Hello”);
Clear method Use to empty the ComboBox list
Example: comboBox1.Items.Clear();

2015 Oct 6FOOP Slide 2-38


We use Timer to Create Animation

2015 Oct 6FOOP Slide 2-39


Timer-Tick private void timer1_Tick(object sender, EventArgs e)
method is { if (pictureBox1.Visible == false)
{
called by pictureBox1.Visible = true;
pictureBox2.Visible = false;
Windows pictureBox3.Visible = false;
}
else if (pictureBox2.Visible == false)
{
Note: pictureBox1.Visible = false;
Timer is pictureBox2.Visible = true;
disabled by pictureBox3.Visible = false;
}
default!
else
{
pictureBox1.Visible = false;
pictureBox2.Visible = false;
pictureBox3.Visible = true;
}
}

2015 Oct 6FOOP Slide 2-40


Case Study: Meal Ordering
This program allows the user to:
 Order the required set meals.

 Choose the required drink.

 Delete or cancel the order.

2015 Oct 6FOOP Slide 2-41


Meal Ordering: User Interface + Demo

Combo box Text box

Picture
Radio
boxes
buttons
Check
box

Group
boxes Buttons

List box

Labels (only
appears after
use press Select an order and press “Delete” to delete the order
“confirm”
Press “Cancel” to remove all order (i.e. cancel everything).

2015 Oct 6FOOP Slide 2-42


Meal Ordering :
User Interface Design and Controls
 For Input
 Key in the quantity (TextBox)
 Select a particular set of meal (ComboBox)
 Select a particular drink (RadioButton)
 Select with/without milk or sugar (CheckBox)
 Confirm to order, delete, cancel, exit (Button)
 For Output
 Display Order (ListBox)
 Display the confirmation (Label)
 Display picture (PictureBox)

2015 Oct 6FOOP Slide 2-43


Summary
A control has many properties, methods, & can response to event:
 Label is used to display messages
 TextBox is used for user input.
 CheckBox and RadioButton allows user to select options. In a
group of RadioButtons, only one can be selected but for
CheckBox, multiple options can be selected.
 GroupBox are used as containers for other controls.
 PictureBox display graphic.
 ComboBox and ListBox are used to display a list of items.
 When a Button is clicked, it triggers an event.

2015 Oct 6FOOP Slide 2-44

Das könnte Ihnen auch gefallen