0% found this document useful (0 votes)
4 views81 pages

Edp CH-4

Chapter 4 of the document covers Event Driven Programming in C# with a focus on GUI development using Windows Forms. It explains various controls, event handling, and layout management, providing detailed information on components such as buttons, text boxes, labels, and more. Additionally, it introduces advanced elements like menus, calendar controls, and tree views, along with methods for automatic layout adjustments.

Uploaded by

mnesru968
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)
4 views81 pages

Edp CH-4

Chapter 4 of the document covers Event Driven Programming in C# with a focus on GUI development using Windows Forms. It explains various controls, event handling, and layout management, providing detailed information on components such as buttons, text boxes, labels, and more. Additionally, it introduces advanced elements like menus, calendar controls, and tree views, along with methods for automatic layout adjustments.

Uploaded by

mnesru968
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

Event Driven Programming (CoSc4062)

Chapter 4
GUI using C#
2
Chapter 4 outlines:
▪ Introduction
▪ Windows Forms
▪ Event Handling
▪ Control Properties and Layout
▪ Labels, TextBoxes and Buttons
▪ GroupBoxes and Panels
▪ CheckBoxes and RadioButton
▪ Controls (Listbox, Combobox, Menus, Tabs, etc.)
▪ Multiple Document Interface (MDI) Windows
Introduction
3
► GUI (Graphical User Interface) allows the user to interact visually with a program.
► Windows applications use different GUI controls to interact with the user.
► They display information on the screen, or enables users to interact with an application
via the mouse, keyboard or other form of input.
► Windows application development uses [Link] namespace to create
forms and other GUI controls.
► This namespace contains all of the controls used on the average Windows interface.
► The commonly used GUI controls include Form, Label, TextBox, Button, Menu,
CheckBox, ComboBox, ListBox, Treeview, ListView, e.t.c.
► Each control has properties (and some methods). E.g. properties: Enable, Font, Text,Visible;
E.g. methods: Hide, Select, Show
Introduction (Cont’d)
4
5
Naming Controls
► InC#, default names for controls/components are: button1, label1,
textbox1, etc. not very descriptive (“generic”)
► Use better, descriptive names—Names to have meanings that make sense
► Conventions for naming controls - start the control name with short
notation of the name of the control
Naming Controls
6
• Control • Begin name with
– Button – btn
– TextBox – txt
– ListBox – lbox
– Label – lbl
– SaveFileDialog – sfd
– Form – frm

Examples of Naming Controls


– A button used to calculate a total:
– btnCalcTotal
– A textbox that allows a user to enter name:
– txtEnterName
Form Class 7
► This is the top-level window class
► A Form is a graphical element that appears on your computer’s desktop; it can be a dialog,
a window or an MDI window (multiple document interface window)
► This class contains all other controls
► Normally, your top-level form inherits from the Form class
► Although the class has numerous methods, most of the time you interact with it via
properties and delegates
8
Form Properties
Property Description
Location Point of to left corner
Size Size of form in pixels
Text Text displayed or caption
BackColor Background color
ForeColor Foreground or drawing color
ControlBox A collection of controls owned by the form
WindowState Whether maximized, minimized or normal
MinimumSize Minimum size window can be resized to
MaximumSize Maximum size window can be resized to
Form Events 9
► GUIs are event driven. GUI to indicate the tasks that the app should perform.
► Forms provide support for a large number of events
► You add one or more delegates to these events
► When the event happens, the delegates are invoked. Event handlers are
connected to a control’s events via special objects called delegates.
► GUI controls have predefined delegates that correspond to every event they can
generate.
► The delegates must have the signature of an event handler.
public delegate void EventHandler( object sender, EventArgs e );
► An event sender calls a delegate object like a method.
new [Link](this.clickButton_Click);
► This indicates that clickButton_Click will respond when a user clicks the
Button.
Form Events (Cont’d)
10

Event Description
Load Just before form is loaded the first time
Closing Just before the form is closed
Closed When the form is actually closed
Shown Occurs when a form is first displayed
ResizeBegin Resize operation has begun
ResizeEnd Resize operation has ended
Form Methods
11

Method Description
Activate Activates the window and gives it focus
Close Closes the form
Show Makes the form visible
BringToFront Moves to top of stacking order
Hide Makes the form invisible
Focus Gives the form focus
Label
12
► Labels are one of the most frequently used C# control.
► We can use the Label control to display text in a set location on the page.
► Label controls can also be used to add descriptive text to a Form to provide the
user with helpful information.
► The Label class is defined in the [Link] namespace.
TextBox
13
► This is a single line or multi-line text editor
• Multiline – get/set Boolean to make multiline
• AcceptsReturn – in a multiline box, if true then pressing Return will create a
new line. If false then the button referenced by the AcceptButton property
of the form, will be clicked.
• PasswordChar – if this is set to a char, then the box becomes a password box
• Text– get/set text from/to textbox.
e.g. [Link] = “[Link]
string var = [Link];
TextBox (Cont’d)
14
• ReadOnly – if true, the control is grayed out and will not accept user input
• ScrollBars – determines which scrollbars will be used: [Link],
Vertical, Horizontal, Both
• TextAlign – get/set [Link], Center, or Right
• TextChanged – event raised when the text is changed
GroupBox
15

► Displays a border around a group of controls

► Can have optional label controlled by Text property

► Controls can be added by

• Placing them within the group box in the designer

• Adding to the Controls list programmatically


Panels
16
► A panel is like a group box but does not have a text label
► It contains a group of controls just like group box
• BorderStyle – get/set border style as
• BorderStyle.Fixed3D
• [Link]
• [Link]
CheckBoxes
17

► Labeled boxes which can be checked or unchecked


• Checked – get/set Boolean to determine if box is checked

• CheckedChanged – delegate called when the box is checked or unchecked


Radio Buttons
18

► Radio buttons are similar to checkboxes, but


• Appear slightly different
• Allow buttons to be grouped so that only one can be checked at a time
► A group is formed when the radio buttons are in the same container – usually a
group box or panel
• Checked – get/set Boolean indicating if the button is checked
• CheckedChanged – delegate invoked when the button is checked or
unchecked
Image Class
19
► An abstract class that can store an image.
► Several concrete classes are used for image types such as BMP, GIF, or JPG.
• FromFile(string fname) – loads any supported image format from a file
• FromStream(stream) – loads an image from a stream
• Height – image height
• Width – image width
PictureBox Class
20
► This displays an image
• Image – assigned an Image object to display
• SizeMode – determines what to do if the image does not fit into the window
o Normal
o StretchImage
o AutoSize
o CenterImage
o Zoom
ToolTips
21
► These are the small pop-up boxes which explain the purpose of a
control.
► ToolTips—the helpful text that appears when the mouse hovers over an
item in a GUI.
NumericUpDown
22

► This allows the selection of an integer from a limited range


► Also called a spinner
• Minimum – smallest selectable value
• Maximum – largest selectable value
• Increment – size of increment per click
• Value – the selected value
• ValueChanged – event raised when the value changes
Exercise 1
23
► Create a C# Windows Forms application that implements a simple calculator
below.
24

GUI with Windows Forms: Part 2


25
GUI with Windows Forms Part 2:
▪ Menus
▪ MonthCalendar and DateTimePicker controls
▪ LinkLabels
▪ ListBox
▪ CheckedListBox
▪ ComboBoxes
▪ TreeView
▪ Other important GUI elements—tab controls and multiple
document interface (MDI) windows
▪ Adding Layout
Menus
26
► Pulldown menus provide a way to select commands and options
► Normally these are in a MenuStrip across the top of the application
► Begin by placing a MenuStrip across the application
► It displays boxes into which menu items and cascading menus can be typed
► The type here text allows new items to be added
► When you click on type here a pull down appears letting you select
• Menu item
• ComboBox
• TextBox
MenuItem Properties
27
► Checked – if true displays check mark
► CheckOnClick – check state changes when clicked
► CheckState – one of
• [Link]
• [Link]
• [Link]
► ShortcutKeys – a member of the Shortcut enumeration indicating the
shortcut key
► Click – event which is raised when the menu item is clicked
► Menu items are similar to buttons and are handled in the same way
ComboBox Menu Items
28
► You can use a ComboBox as a menu item

► Use the designer to add a set of Items to the combo box


► You can then select a value
► The click event is raised only when you click on the selected value, not when you
change the selection
► If you have nothing selected, the selected item will be null
MonthCalendar
29

► A control which displays a calendar for the selection of a range of dates


• MinDate – the first selectable date

• MaxDate – the last selectable date


• SelectionStart – DateTime of start of selection
• SelectionEnd – DateTime of end of selection

• DateChanged – event raised when date is changed


DateTimePicker
30
► Similar to a month calendar but
• Calendar pulls down and selection displayed
• More configurable
• Selects a single value, not a range
► Properties/methods
• Format – Long, Short, Time, Custom
• Value – DateTime value selected
• ValueChanged – event which fires when date or time changes
TreeView
31
► Presents a hierarchical tree view of the data
► Nodes can be
• Selected
• Expanded and collapsed
► Text of nodes can be edited
► Nodes can be added or deleted programmatically
TreeNode
32
► All nodes in the tree are instances of TreeNode
► Constructors
• TreeNode(string displayText)

► Properties
• Nodes – get TreeNodeCollection of all children of this node

• Text – the displayed text

• Checked – true if the node is checked

• FullPath – the labels of all nodes from the root to this node separated by
“\\”
TreeNode (Cont’d)
33
• NextNode – returns next sibling
• PrevNode – returns previous sibling
► Methods
• Collapse – collapses the node
• Expand – expands the node
• ExpandAll – expands all children of this node
• GetNodeCount – returns the number of child nodes
TreeView (Cont’d)
34
► This is the actual control
► Properties
• Nodes – get TreeNodeCollection of all children of this node
• CheckBoxes – if true, displays checkboxes beside tree nodes
• SelectedNode – the selected node
• LabelEdit – if true, node text can be edited
► Events
• AfterSelect – after a node is selected
• AfterExpanded – after a node is expanded
• AfterCollapsed – after a node is collapsed
• AfterEdited – after a node is edited
Populating a TreeView
35
1. Usually, create a root TreeNode
2. Add the root node onto the Nodes collection of the TreeView
3. Create a child TreeNode and add it to the Nodes collection of the root node
4. Continue this way to build whole tree
TreeView tv = new TreeView();
TreeNode root = new TreeNode(root);
[Link](root);
[Link](new TreeNode(“Vegetables”));
[Link](new TreeNode(“Fruit”));
[Link](new TreeNode(“Meat”));
[Link](new TreeNode(“Poultry”));
TabControl
36
• Displays a series of tabs
• Each tab is a different page with its own controls on it
• Each tab is like a group box or panel
• Create
• In Visual Studio
• Drop controls into the tab pages
• Set the text property of every page to change the label
• Right click on a tab and select “Add Tab” to add a new tab
• Multiline – if true tabs can be in several lines
• SelectedIndex – index of selected tab
• SelectedTab – the selected tab
• TabPages – collection of TabPages
• SelectedIndexChanged – event raised when a different tab is selected
MessageBox
37
► A pop-up dialog which displays a message
• [Link]("Yes No Cancel Message Box Click one?", "Yes No Cancel
Buttons", [Link],[Link]);
► The following are the different messagebox
DialogResult
38
• Is used to get the type of button DialogResult dr=new DialogResult ();
clicked on the messagebox dr=[Link]("Yes No Cancel Message Box Click one?",
"Yes No Cancel Buttons", [Link],
• The following are the results that [Link]);
can be retrieved using if (dr == [Link])
• Abort {
[Link]("Yes Button Clicked!");
• Cancel }
• Ignore else if (dr == [Link])
{
• No [Link]("No Button Clicked!");
}
• None else if (dr == [Link])
• OK {
[Link]("Cancel Button Clicked!");
• Retry }
• Yes
Automatic Layout
39
► All of the forms we have seen so far have been laid out based on X-Y
coordinates
► If the outer form is resized, the contents stay at the same size and position
► There are three ways to change this
• The Dock property
• The FlowLayoutPanel
• The TableLayoutPanel
The Dock Property
40
► Everycontrol has a Dock property which
can be set to
• None – no docking
• Left – docked to left side of container
• Right – docked to right side of container
• Top – docked to top of container
• Bottom – docked to bottom of container
• Fill – fills all available space
► When controls are docked to the sides of
their containing form, resizing the form
resizes the controls inside as well
FlowLayoutPanel
41
► Arranges its contents into
horizontal or vertical rows
► As form is resized, controls are
arranged into new rows or
columns
► Created in designer by dropping
controls into it
► In designer it has small arrow on
the top that activates menu of
editing actions
FlowLayoutPanel (Cont’d)
42
► FlowDirection – layout direction
• BottomUp
• TopDown
• LeftToRight
• RightToLeft
► WrapContents – whether the contents should be wrapped to a new row or
column or clipped
TableLayoutPanel
43
► Arranges the controls within it into rows and columns
► Automatically resizes contents when the surrounding form is resized
► The pull-out menu in designer can be used to add or delete rows and columns
• ColumnCount – get/set number of columns
• RowCount – get/set number of rows
44

LinkLabel Control
45
LinkLabel control
► The LinkLabel control displays links to other resources, such as files or web
pages
► A LinkLabel appears as underlined text (colored blue by default).
► When clicked, the LinkLabel generates a LinkClicked event
► Class LinkLabel is derived from class Label and therefore inherits all of class
Label’s functionality.
LinkLabel control properties and events
46
LinkLabel control: Example 47
LinkLabel control: Example
48
using System;
using [Link];
namespace LinkLabelTest
{
public partial class LinkLabelTestForm : Form
{
public LinkLabelTestForm()
{
InitializeComponent();
}
private void lnkCDrive_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
[Link]=true;
[Link](@"C:\");
}
private void lnkDeitel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
[Link] = true;
[Link]("[Link]
}
LinkLabel control: Example
49
private void lnkNotepad_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
[Link] = true;
[Link]("notepad");
}

private void lnkForm2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)


{
[Link] = true;
Form2 f2 = new Form2();
[Link]();
}
}
}
LinkLabel control (Cont’d)
50
► Common Windows applications and their corresponding executable names used in the [Link] method:
• File Explorer: [Link]
• Notepad: [Link]
• Calculator: [Link]
• Paint: [Link]
• Command Prompt: [Link]
• PowerShell: [Link]
• Task Manager: [Link]
• Registry Editor: [Link]
• Microsoft Edge: [Link]
• Internet Explorer: [Link]
• WordPad: [Link]
• System Information: [Link]
• Remote Desktop: [Link]
• DirectX Diagnostic Tool: [Link]
• Disk Cleanup: [Link]
• Microsoft Word: [Link] (if installed).
• Microsoft Excel: [Link] (if installed).
ListBox control 51
► The ListBox control allows the user to view and select from multiple items in a list.
► ListBoxes are static GUI entities, which means that users cannot directly edit the list of
items.
► The user can be provided with TextBoxes and Buttons with which to specify items to be
added to the list, but the actual additions must be performed in code.
► The CheckedListBox control extends a ListBox by including CheckBoxes next to each
item in the list
ListBox control (Cont’d)
52
ListBox control (Cont’d)
53
► Both the ListBox and CheckedListBox have properties Items, SelectedItem and
SelectedIndex.
► Property Items returns a collection of the list items.
► Collections are a common way to manage lists of objects in the .NET
framework.
► Property SelectedIndex returns the index of the selected item.
► If no items are selected, property SelectedIndex returns -1.
► Method GetSelected takes an index and returns true if the corresponding item
is selected.
Adding Items to ListBoxes and CheckedListBoxes
[Link]( myListItem );
ListBox control: Example
54
ListBox control: Example
55
ListBox control: Code behind
using System;
56
using [Link];
namespace LinkLabelTest1
{
public partial class frmLinkLabelTest1 : Form
{
public frmLinkLabelTest1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
[Link]([Link]);
[Link]();
}
private void btnRemove_Click(object sender, EventArgs e)
{
if ([Link] != -1)
[Link]([Link]);
}
private void btnClear_Click(object sender, EventArgs e)
{
[Link]();
}
private void btnExit_Click(object sender, EventArgs e)
{
[Link]();
}
}
}
CheckedListBox control
57
► The CheckedListBox control derives from ListBox and displays a CheckBox with
each item.
► CheckedListBoxes allow multiple items to be checked, but item selection is more
restrictive.
► The only values for the SelectionMode property are None and One. One
allows a single selection, whereas None allows no selections.
► Event ItemCheck occurs whenever a user checks or unchecks a CheckedListBox
item.
► The CheckedListBox control retains the SelectedItems and SelectedIndices
properties.
CheckedListBox control: Example
58
CheckedListBox control: Code Behind 59
using System;
using [Link];
namespace LinkLabelTest1
{
public partial class CheckedListBoxTest : Form
{
public CheckedListBoxTest()
{
InitializeComponent();
}
private void clsbItem_ItemCheck(object sender, ItemCheckEventArgs e)
{
string item = [Link]();
if ([Link] == [Link])
[Link](item);
else
[Link](item);
}
}
}
ComboBox control
60
► 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.
► The maximum number of items that a drop-down list can display at one time is
set by property MaxDropDownItems.
ComboBox control (Cont’d)
61
ComboBox control: Example 62
ComboBox control: Code Behind
using System;
using [Link];
63
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace LinkLabelTest1
{
public partial class ComboBoxTest : Form
{
public ComboBoxTest()
{
InitializeComponent();
}
private void cmbImage_SelectedIndexChanged(object sender, EventArgs e)
{
Graphics myGraphics = [Link]();
Pen myPen = new Pen([Link]);
SolidBrush mySolidBrush = new SolidBrush( [Link] );
[Link]([Link]);
switch ([Link])
{
case 0:
[Link](myPen, 50, 50, 150, 150);
break;
ComboBox control: Code Behind (Cont’d)
case 1: 64
[Link](myPen, 50, 50, 150, 150);
break;
case 2:
[Link](myPen, 50, 85, 150, 115);
break;
case 3:
[Link](myPen, 50, 50, 150, 150, 0, 45);
break;
case 4:
[Link](mySolidBrush, 50, 50, 150, 150);
break;
case 5:
[Link](mySolidBrush, 50, 50, 150, 150);
break;
case 6:
[Link](mySolidBrush, 50, 85, 150, 115);
break;
case 7:
[Link]( mySolidBrush, 50, 50, 150, 150, 0,45);
break;
}
}
}
}
ListView control
65
► The ListView control is similar to a ListBox in that both display lists from which the user
can select one or more items.
► ListView is more versatile and can display items in different formats. For example, a
ListView can display icons next to the list items (controlled by its SmallImageList,
LargeImageList or StateImageList properties) and show the details of items in
columns.
► Property MultiSelect (a bool) determines whether multiple items can be selected.
CheckBoxes can be included by setting property CheckBoxes (a bool) to true, making
the ListView’s appearance similar to that of a CheckedListBox.
► The View property specifies the layout of the ListBox.
► Property Activation determines the method by which the user selects a list item.
► ListView allows you to define the images used as icons for ListView items.
ListView control: Example
66
ListView control: Code Behind
private void btnSave_Click(object sender, EventArgs e) 67
{
if ([Link] != "" && [Link] != "" && [Link] != "" &&
[Link] != 0 && [Link] != 0)
{
int age = [Link]([Link]);
if (age >= 15){
int i = 0;
string[] st = new string[6];
st[0] = [Link];
st[1] = [Link];
st[2] = [Link]();
st[3] = [Link];
st[4] = [Link]();
st[5] = [Link]();
ListViewItem item = new ListViewItem(st);
[Link](item);
[Link]("Student Data Saved Successfully!", "Successfull",
[Link], [Link]);
}
ListView control: Code Behind (Cont’d)
68
else
{
[Link]("Sorry, you are not eligible for registration!",
"Not Elligible", [Link],
[Link]);
}
}
else
{
[Link]("Please, fill all fields!", "Required Field",
[Link], [Link]);
}
}
ListView control: Code Behind (Cont’d)
69
private void btnReset_Click(object sender, EventArgs e)
{
[Link] = "";
[Link] = "";
[Link] = "";
[Link] = 0;
[Link] = 0;
[Link] = 0;
}
private void btnCancel_Click(object sender, EventArgs e)
{
[Link]();
}
ListView control: Code Behind (Cont’d)
70
public frmStudent()
{
InitializeComponent();
}
private void frmStudent_Load(object sender, EventArgs e)
{
[Link] = 0;
[Link] = 0;
[Link] = 0;
[Link] = [Link];

[Link]("ID", 100);
[Link]("Name", 70);
[Link]("Sex", 70);
[Link]("Age", 70);
[Link]("Department", 70);
[Link]("Program", 70);
}
71

Multiple Document Interface (MDI)


Multiple Document Interface (MDI)
72
► Many complex apps are multiple document interface (MDI) programs, which
allow users to edit multiple documents at once (e.g., Microsoft Office products).

► An MDI program’s main window is called the parent window, and each window
inside the app is referred to as a child window.

► Although an MDI app can have many child windows, each has only one parent
window. Furthermore, a maximum of one child window can be active at once.

► Child windows cannot be parents themselves and cannot be moved outside their
parent. Otherwise, a child window behaves like any other window (with regard
to closing, minimizing, resizing, and so on).
MDI (Cont’d) 73
MDI (Cont’d)
74
► To create an MDI Form, create a new Form and set its IsMdiContainer
property to true.

► In general, to add a child Form to a parent, write:


ChildFormClass childForm = New ChildFormClass();
[Link] = parentForm;
[Link]();
► Class Form property MdiChildren returns an array of child Form
references.
► Property ActiveMdiChild returns a reference to the active child window;
it returns null if there are no active child windows.
MDI (Cont’d)
75
MDI: Example
76
MDI: Example (Cont’d)
77
MDI: Code Behind (Parent Window) 78
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace UsingMDI
{
public partial class mdiForm1 : Form
{
public mdiForm1()
{
InitializeComponent();
}
private void lacendarFlowersToolStripMenuItem_Click(object sender, EventArgs e)
{
ChildForm child = new ChildForm("Lavender Flowers", "lavenderflowers");
[Link] = this; // set parent
[Link]();
}
}
}
MDI: Code Behind (Child Window) 79
using System;
using [Link];
namespace UsingMDI
{
public partial class ChildForm : Form
{
public ChildForm(string title, string name)
{
InitializeComponent();

[Link] = title; // Set window title


// You can use 'name' however you want
}
}
}
Read: Reference 1 80

Chapter 14 – GUI with Windows Forms: Part 1


Chapter 15 – GUI with Windows Forms: Part 2

You might also like