0% found this document useful (0 votes)
10 views78 pages

Lecture 4 V2

The document provides a comprehensive overview of various controls in C# programming, including ListBox, CheckListBox, ComboBox, NumericUpDown, ToolTip, and LinkLabel. It includes examples and properties for creating a calculator application, handling user input, and managing events. Additionally, it covers best practices and common programming errors associated with these controls.

Uploaded by

Ahmed Al-nasheri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views78 pages

Lecture 4 V2

The document provides a comprehensive overview of various controls in C# programming, including ListBox, CheckListBox, ComboBox, NumericUpDown, ToolTip, and LinkLabel. It includes examples and properties for creating a calculator application, handling user input, and managing events. Additionally, it covers best practices and common programming errors associated with these controls.

Uploaded by

Ahmed Al-nasheri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Dr.

Ahmed Alnasheri
Contents
 Review  ListBox
 Example:  CheckListBox
 Calculator  ComboBox
 NumericUpDown  DateTimePicker.
 ToolTips  Mouse Events
 LinkLabel  Keyboard Events

2
Create Calculator Application
 Name your form “ My C# Calculator”
 Add textbox, and some buttons, so that your form will
be as follow:

3
The First Code after double click on btn0

4
Clear button
 In side the btn_clear_Click Method assign total1 to zero

5
Populate The rest of buttons

6
The +, -, *, /, and = Buttons
 Declare two variables (total1 = 0, total2=0) as double
 Declare four variables as Boolean and initialize them

Why

 The code on clicking each of (+, -, *, /) will be look like:

Add the 4
Boolean
Here variables

7
The +, -, *, /, and = Actions

The
code
inside
the =
button
will be
look
like

8
Good Practice
Redo the pervious
calculator Application using
switch case control instead
of if else if
1. a char.
2. a string.
3. a bool.
4. an integral value, such as an int or a long.
5. an enum value.
9
NumericUpDown Control
 NumericUpDown: is used as a counter, it has a numeric
value that can be incremented and decremented using
arrows, and the user can also write a certain value in it, as
long as it is within the minimum and maximum values.
 Restrict a user’s input choices to a specific range of numeric values.

 Appears as a TextBox, with two small Buttons on the right side

 NumericUpDown’s ReadOnly property indicates if user can type a


number into the control

10
NumericUpDown - Properties
 Value: the current numeric value displayed on the control.
 Minimum: The minimum value allowed in the
NumericUpDown.
 Maximum: The maximum value allowed in the
NumericUpDown.
 Increment: The amount added or subtracted from the
value when using the arrows.
 DecimalPlaces: Number of decimal places displayed in
the value. (the default is 0). If the decimal places is more
that 0, then you can set Increment property to a fraction
number. (i.e. you can increase and decrease by 0.5).

11
NumericUpDown – Default Event
 ValueChanged: Occurs when the value is changed
either by using the arrows, or by writing on it, or
changed in code.

12
NumericUpDown Example
1 // Fig. 13.36: interestCalculatorForm.cs
2 // Demonstrating the NumericUpDown control.
3 using System;
4 using System.Windows.Forms;
5
6 public partial class interestCalculatorForm : Form
7 {
8 // default constructor
9 public interestCalculatorForm()
10 {
11 InitializeComponent();
12 } // end constructor
13
14 private void calculateButton_Click(
15 object sender, EventArgs e )
16 {
17 // declare variables to store user input
18 decimal principal; // store principal
19 double rate; // store interest rate Retrieve, convert, and assign
20 int year; // store number of years principalTextBox,
decimal amount; // store amount
21
InterestTextBox, and
22 string output; // store output
23 yearUpDown’s values
24 // retrieve user input
25 principal = Convert.ToDecimal( principalTextBox.Text );
26 rate = Convert.ToDouble( interestTextBox.Text );
27 year = Convert.ToInt32( yearUpDown.Value );
13
NumericUpDown Example
28
29 // set output header
30 output = "Year\tAmount on Deposit\r\n";
31
32 // calculate amount after each year and append to output
33 for ( int yearCounter = 1; yearCounter <= year; yearCounter++ )
34 {
35 amount = principal *
36 ( ( decimal ) Math.Pow( ( 1 + rate / 100 ), yearCounter ) );
37 output += ( yearCounter + "\t" +
38 string.Format( "{0:C}", amount ) + "\r\n" ); Calculate interest and
} // end for
39
40
format it as a String
41 displayTextBox.Text = output; // display result
42 } // end method calculateButton_Click
43 } // end class interestCalculatorForm Output results in
displayTextBox
Click to increase
number of years

NumericalUpDown
control

Click to decrease
number of years
14
ToolTip
 ToolTip: is a hint added to a certain control, you can
use to give a certain tip or help to the user.

 The tooltip is not an ordinary control, since it is added


to a tray in your project, and doesn’t occupy a space on
the form.

 You can create a tooltip, and set its property, then


associate it to several controls.

15
ToolTip Creation
 To create a tooltip, just double click on it, and it will be
added to the project tray.

At Run Time

16
ToolTip Properties:
 AutoPopDelay: Determines the length of time a
certain tooltip window remains visible when the
mouse hovers over a certain control.
 InitialDelay: Determines the length of time the
pointer must remain on a certain control to display the
tooltip window.
 AutomaticDelay: According to the number inserted,
both AutoPopDelay and InitialDelay are automatically
set.

17
ToolTip Text
 When you add the ToolTip on your project, a new
property will be added to all controls on your form,
where you can add the text you desire to appear when
hovering over this control with the mouse.

18
Tool TipExampleForm.cs
1 // Fig. 13.32: ToolTipExampleForm.cs
2 // Demonstrating the ToolTip component.
3 using System;
4 using System.Windows.Forms;
5
6 public partial class ToolTipExampleForm : Form
7 {
8 // default constructor

Property to set tool tip


9 public ToolTipExampleForm()
10 {

Tool tip text


11 InitializeComponent();
12 } // end constructor
13
14 // no event handlers needed for this example

text
15

19
LinkLabel
 LinkLabel: is an active label (non-edited text), that
appears to the user with a special behavior (as a link on
a website). It can be used to open a file or run a certain
program.

Label

LinkLabel

20
LinkLabel - Properties
 LinkColor: The original color of the linklabel (Blue by default).
 ActiveLinkColor: The color of the linklabel when clicking on it
using mouse. (Red by default).
 VisitedLinkColor: The color of the linklabel after visiting the
destination. (Purple by default).
 LinkVisited: of type bool; when true, the linklabel takes the
color set in VisitedLinkColor, otherwise, it will be displayed in
the LinkColor.
 LinkBehavior: Determines the look of the linklabel when the
mouse hovers over it (AlwaysUnderline, HoverUnderline,
NeverUnderline).
 LinkArea: Determines the active area of the linklabel text. It
consists of “Start: which position to start the link area” and
“Length: number of characters to be included in the link area”.

21
LinkLabel – Default Event and
Method
 LinkClicked: Occurs when the user clicks on the
linklabel using mouse.
 To activate a link, call a method “Start”, from class
“Process” from namespace “System.Diagnostics”, and
send the name of the program you want to start.
(Note: when writing the name of a program, use the
name of the .exe file on your computer).

22
LinkLabel - Method
1
2
3
4

1. Opens Philadelphia University website in the default browser.


2. Opens Philadelphia University website using Internet Explorer.
3. Opens the Calculator Program
4. Opens folder “Sample Pictures”.

23
Look-and-Feel Observation

A LinkLabel is the preferred control for indicating


that the user can click a link to jump to a resource such
as a Web page, though other controls can perform
similar tasks.

24
LinkLabel Example
1 // Fig. 14.14: LinkLabelTestForm.cs
2 // Using LinkLabels to create hyperlinks.
3 using System;
4 using System.Windows.Forms;
5
6 // Form using LinkLabels to browse the C:\ drive,
7 // load a webpage and run Notepad
8 public partial class LinkLabelTestForm : Form
9 {
10 // default constructor
11 public LinkLabelTestForm()
12 {
13 InitializeComponent();
14 } // end constructor
15
16 // browse C:\ drive
17 private void driveLinkLabel_LinkClicked( object sender,
18 LinkLabelLinkClickedEventArgs e )
19 { Change the color of the link
20 // change LinkColor after it has been clicked
to show that it has already
21 driveLinkLabel.LinkVisited = true;
22
been clicked before
23 System.Diagnostics.Process.Start( @"C:\" );
24 } // end method driveLinkLabel_LinkClicked Open the C: folder
25
LinkLabelTestForm.cs

26
LinkLabelTestForm.cs

27
LinkLabel TestForm.cs

28
ListBox
 ListBox: a control used to add several items in it,
either at design time, or at run time. A user can select
among these items according to the requirement of
the application.

 Static GUI entities

29
ListBox - Properties
 Items: Either from the property sheet, or from Edit
Items options on the Listbox itself.
 You can add item using the String Collection Editor,
separate the items by “Enter”.

 Items property, is considered a collection (array), where


you can access a certain item by its index.

30
ListBox - Properties
 SelectionMode: Determines number of items a user
can select from the listbox.
 One (single-selection)
 MultiSimple (Multi-selection, using mouse only)
 MultiExtended (Multi – selection using mouse along
with Ctrl or Shift keys)
 Sorted: of type bool; if true, the items will be sorted
from A-Z.

31
ListBox - Properties
 SelectItem: a run-time property, that retrieves the
current selected item (as an object).
 If more than one item is selected, this property will
retrieve the first selected item in the listbox.
 SelectedIndex: a run-time property, that retrieves the
current selected index (as an int). (Note: will return -1
if there is no selection).
 If more than one item is selected, this property will
retrieve the index of the first selected item in the listbox.

32
ListBox - Properties
 SelectedItems: a run-time property, is a collection
(array) of objects, that contains all the selected items
in a special array (different index than Items array).
 SelectedIndecies: a run-time property, is a collection
(array) of integers that represent indecies of selected
items.
 listBox1.Items.Count: a run-time property, that
returns the number of items in a listbox.
 listBox1.SelectedItems.Count: a run-time property,
that returns the number of selected items in a listbox.
33
ListBox – Default Event
 SelectedIndexChanged: Occurs when the user
selects a different item.

34
ListBox - Methods
 GetSelected(index): Takes an index as a parameter,
and returns true if it is selected, and false if not.
 listBox1.Items.Add (object/text): Adds a new item
in a listbox.
 listBox1.Items.AddRange(Items): Adds an array of
items in the listbox.
 listBox1.Items.Remove(Object): Removes the first
occurrence of the passed item.
 listBox1.Items.RemoveAt(Index): Removes the first
occurrence of the passed index.
35
ListBox - Methods
 listBox1.Items.Clear(): Removes all items in a listBox.
 listBox1.ClearSelected(): Cancel the selection of
items in a listBox (i.e. sets the SelectedIndex property
to -1).

36
ListBox Example

37
ListBox Example

38
ListBox Example

39
CheckListBox
 CheckListBoxes
 Extend ListBox
 Include CheckBoxes next to each item in the list
 Multiple items can be selected
 SelectionMode property
 Only possible values are None and One
 Give the user multiple selection or no selection at all

 Behavior consistent with that of CheckBoxes

 Event ItemCheck
 Occurs whenever a user checks or unchecks a
CheckedListBox item
40
Common Programming Error
The IDE displays an error message if you attempt to set
the SelectionMode property to MultiSimple or
MultiExtended in the Properties window of a
CheckedListBox. If this value is set programmatically, a
runtime error occurs.

41
CheckListBox Properties
CheckedListBox
properties, methods and
events Description

Common Properties (All the ListBox properties, methods and


events are inherited by
CheckedListBox.)
CheckedItems Contains the collection of items that are
checked. This is distinct from the selected
item, which is highlighted (but not
necessarily checked). [Note: There can be
at most one selected item at any given
time.]
CheckedIndices Returns indices for all checked items.
SelectionMode Determines how many items can be
checked. The only possible values are One
(allows multiple checks to be placed) or
None (does not allow any checks to be
placed).
Common Method
GetItemChecked Takes an index and returns true if the
corresponding item is checked.
Common Event (Event arguments ItemCheckEventArgs)
ItemCheck Generated when an item is checked or
unchecked.

42
CheckListBox Event

CheckedListBox
properties, methods and
events Description

ItemCheckEventArgs Properties
CurrentValue Indicates whether the current item is
checked or unchecked. Possible values are
Checked, Unchecked and
Indeterminate.
Index Returns the zero-based index of the item
that changed.
NewValue Specifies the new state of the item.

43
CheckListBox Example

44
CheckListBox Properties
(a)
(c)

(b) (d)

45
ComboBox
 ComboBox: a control used to add several items in it,
either at design time, or at run time. A user can select
only one items among these items.

46
ComboBox - Properties
 Items: Either from the property sheet, or from Edit
Items options on the ComboBox itself.
 You can add item using the String Collection Editor,
separate the items by “Enter”.

 Items property, is considered a collection (array), where


you can access a certain item by its index.

47
ComboBox- Properties
 Sorted: of type bool; if true, the items will be sorted from A-Z.
 Text: A string represents the selected item.
 Dropdownstyle: The way the ComboBox displays the items in it.
 DropDown: In this style, the user can write
an Item in the combobox or select an existing item.

 DropDownList: In this style the user cannot write in it,


but can select one item from the combobox.

 Simple: It looks like a listbox, but


Though a user cannot select more than
One item.

48
ComboBox- Properties
 SelectItem: a run-time property, that retrieves the
current selected item (as an object).
 Combobox doesn’t allow multi-selection of items.
 SelectedIndex: a run-time property, that retrieves the
current selected index (as an int). (Note: will return -1
if there is no selection).

49
ComboBox- Properties
 ComboBox.Items.Count: a run-time property, that
returns the number of items in a listbox.

50
ComboBox– Default Event
 SelectedIndexChanged: Occurs when the user
selects a different item.

51
ComboBox- Methods
 comboBox1.Items.Add (object/text): Adds a new
item in a combobox.
 comboBox1.Items.AddRange(Items): Adds an array
of items in the combobox.
 comboBox1.Items.Remove(Object): Removes the
first occurrence of the passed item.
 comboBox1.Items.RemoveAt(Index): Removes the
first occurrence of the passed index.
 comboBox1.Items.Clear(): Removes all items in a
combobox.
52
Look-and-Feel Observation

Use a ComboBox to save space on a GUI. A disadvantage


is that, unlike with a ListBox, the user cannot see
available items without expanding the drop-down list.

53
ComboBox Example

54
ComboBox Example

55
ComboBox Example

56
Look-and-Feel Observation

Make lists (such as ComboBoxes) editable only if the


program is designed to accept user-submitted elements.
Otherwise, the user might try to enter a custom item that
is improper for the purposes of your application.

57
DateTimePicker
 DateTimePicker
 Displays the calendar when a down arrow is selected
 Retrieve date and time information from user
 More customizable than a MonthCalendar
 More properties are provided to edit the look and feel of the
drop-down calendar
 ValueChanged event
 Occurs when user selects a date

58
DateTimePicker
 DateTimePicker
 Displays the calendar when a down arrow is selected
 Retrieve date and time information from user
 More customizable than a MonthCalendar
 More properties are provided to edit the look and feel of the
drop-down calendar
 ValueChanged event
 Occurs when user selects a date

59
DateTimePicker Properties and Events
DateTimePicker properties
and an event Description

DateTimePicker Properties
CalendarForeColor Sets the text color for the calendar.
CalendarMonthBackground Sets the calendar’s background color.
CustomFormat Sets the custom format string for the user’s options.
Format Sets the format of the date and/or time used for the
user’s options.
MaxDate The maximum date and time that can be selected.
MinDate The minimum date and time that can be selected.
ShowCheckBox Indicates if a CheckBox should be displayed to the
left of the selected date and time.

DateTimePicker properties
and an event Description

ShowUpDown Used to indicate that the control should have up


and down Buttons. This is helpful for instances
when the DateTimePicker is used to select a
time—the Buttons can be used to increase or
decrease hour, minute and second values.
Value The data selected by the user.
Common DateTimePicker Event
ValueChanged Generated when the Value property changes,
including when the user selects a new date or time.
60
DateTimePicker Example

61
DateTimePicker Example

62
DateTimePicker Example
(c) (d)

63
Mouse Events
 Mouse Events: Are those events that associated to
mouse actions. And can be related to the form as a
whole, or to a certain control derives from class
System.Windows.Forms.Control.
 Class MouseEventArgs
 Contains information related to the mouse event
 Information about the event is passed to the event-
handling method through an object of this class
 The delegate used to create the mouse-event handlers
is MouseEventHandler

64
Mouse Events
 MouseMove: occurs when the mouse cursor moves over a form or a
certain control.
 MouseClick: occurs when the user clicks on the form or on certain
control with the mouse button (any button click will cause this event).
 MouseEnter: occurs when the mouse cursor enters in the borders of a
form or a certain control.
 MouseLeave: occurs when the mouse cursor leaves the area of a form
or a certain control.
 MouseDown: occurs when the user presses over a mouse button, and
keeps pressing. (any button).
 MouseUp: occurs when the user releases the mouse button. (any
button).
 MouseHover: occurs when the mouse cursor hovers over a form or a
certain control.

65
Mouse Events Arguments
 According to the mouse event handled, certain events
arguments are used.
 One of two event arguments classes would appear in
the header of the Mouse Event Handler.
 MouseEventArgs: This event arguments class will be
used in the events (MouseClick, MouseMove,
MouseDown and MouseUp), and it contains special
properties of the mouse.
 EventArgs: The ordinary event arguments class, that is
usually associated with any event handler. It doesn’t
contain any special properties of the mouse.

66
MouseEventArgs
 This class will appear in the header of the mouse
events: MouseClick, MouseMove, MouseDown and
MouseUp.

 The argument “e”, which is of class “MouseEventArgs”


will contain the following mouse properties:

67
MouseEventArgs
 X: of type int; and returns the X coordinate of the
mouse cursor over a form or a certain control.
 Y: of type int; and returns the Y coordinate of the
mouse cursor over a form or a certain control.
 Button: of type MouseButtons; which is a
enumeration that has the values (Left, Right and
Middle), which indicate which mouse button was
clicked and caused the event.

68
Mouse Event Example

69
MouseEventArgs

70
Keyboard Events
 Keyboard Events: Are events associated with the
keyboard keys. Whenever a user presses on any key on
the keyboard, these events take place.

71
Keyboard Events
 KeyPress: occurs when the user presses on a certain
key in the keyboard.

 KeyDown: occurs when the user presses on a certain


key in the keyboard and keeps pressing.

 KeyUp: occurs directly when the user releases the key


in the keyboard.

72
Keyboard Events Arguments
 According to the keyboard event handled, certain
events arguments are used.
 One of two event arguments classes would appear in
the header of the keyboard Event Handler.
 KeyPressEventArgs: This event arguments class will be
used in the event KeyPress, and it contains special
properties of the key.
 KeyEventArgs: This event arguments class will be used
in the event KeyDown and KeyUp, and it contains
special properties of the key.

73
KeyPressEventArgs
 The main property retrieved by this class is: KeyChar.

 KeyChar: of type char; it retrieves the actual character printed by the


key pressed. (only printable characters, non-printable characters won’t
retrieve data in this property).

74
KeyEventArgs
 Exists in both KeyDown and KeyUp event handlers.

 Properties enclosed in this class:


 KeyCode: of type Keys; which is an enumeration that contains all
possible keys on the keyboard (printable and non-printable).
 KeyData: of type Keys; but it differs that KeyCode. KeyCode will
return the last pressed key, while KeyData will return all keys
pressed at the same time.
 KeyValue: of type int; returns an integer value that represents the
key on the keyboard.
 Alt: of type bool; returns true if Alt key is pressed, false if not.
 Shift: of type bool; returns ture if Shift key is pressed, false if not.
 Control: of type bool; returns true if Ctrl key is pressed, false if not.

75
Keyboard Event Example

76
Homework 3
 Redo the calculator application with the use of switch
case control instead of if else if selection control.
 Create the following form, with the displayed controls:

77
The End
78

You might also like