C#Unit-4 Notes
C#Unit-4 Notes
C#Unit-4 Notes
Windows Forms:
Introduction to Windows Forms:
Windows Forms is a Graphical User Interface(GUI) class library which is bundled in
.Net Framework.
Its main purpose is to provide an easier interface to develop the applications for desktop,
tablet, PCs.
It is also termed as the WinForms.
The applications which are developed by using Windows Forms or WinForms are
known as the Windows Forms Applications that runs on the desktop computer.
WinForms can be used only to develop the Windows Forms Applications not web
applications.
WinForms applications can contain the different type of controls like labels, list boxes,
tooltip etc.
The Windows Forms framework provides a rich set of controls that developers can use to
build applications with. These controls are designed to provide a consistent and familiar
user interface for Windows users. Developers can customize the appearance and behaviour
of these controls by setting various properties and handling events.
To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which is
an integrated development environment (IDE) that provides a visual designer to create and
layout the user interface elements. The visual designer is a drag-and-drop interface for
building your UI, and you can easily configure each control’s properties through a user-
friendly interface.
In addition to the visual designer, Visual Studio also provides a code editor that enables
developers to write the C# code for the application’s logic. Developers can handle events
and perform tasks such as data validation, data manipulation, and business logic
implementation.
Windows Forms applications are versatile and can be used to create various types of
applications such as data entry, management, and reporting applications, as well as games
and multimedia applications.
Overall, Windows Forms applications provide an easy-to-use and familiar graphical user
interface for Windows users, making it an ideal choice for building desktop applications that
require a high degree of interactivity and user engagement.
Control Properties and Layout
Controls derive from class Control (namespace System.Windows.Forms)
Lists some of class Control's properties and methods. The properties shown here can be set
for many controls. For example, the Text property specifies the text that appears on a
control. The location of this text varies depending on the control. In a Windows Form, the
text appears in the title bar, but the text of a Button appears on its face.
Class Control properties
and methods Description
Common Properties
BackColor The control's background color.
BackgroundImage The control's background image.
Enabled Specifies whether the control is enabled (i.e., if the user can interact
with it). Typically, portions of a disabled control appear "grayed
out" as a visual indication to the user that the control is disabled.
Focused Indicates whether the control has the focus.
Font The Font used to display the control's text.
ForeColor The control's foreground color. This usually determines the color of
the text in the Text property.
TabIndex The tab order of the control. When the Tab key is pressed, the focus
transfers between controls based on the tab order. You can set this
order.
TabStop If true, then a user can give focus to this control via the Tab key.
Text The text associated with the control. The location and appearance of
the text vary depending on the type of control.
Visible Indicates whether the control is visible.
Common Methods
Focus Acquires the focus.
Hide Hides the control (sets the Visible property to false).
Show Shows the control (sets the Visible property to true).
Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New ->
Project -> WindowsFormApp
Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are
allowed to place a Label control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Label control to set the
properties of the Label according to your need.
Labels in C#
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 System.Windows.Forms namespace.
Add a Label control to the form - Click Label in the Toolbox and drag it over the forms
Designer and drop it in the desired location.
If you want to change the display text of the Label, you have to set a new text to the Text
property of Label.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e){
label1.Text = "VCET Puttur.";
label1.BorderStyle = BorderStyle.FixedSingle;
label1.TextAlign = ContentAlignment.MiddleCenter;
}
}
}
Property Description
2. Text Boxes in C#
In Windows forms, TextBox plays an important role.
With the help of TextBox, the user can enter data in the application,
1. Design-Time: It is the simplest way to create a TextBox as shown in the following steps:
Step 1: Create a windows form. As shown in the below image: Visual Studio -> File -> New -
> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You
can place TextBox anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the TextBox control to modify
the TextBox design according to your requirement.
2. Run-Time:
It is a little bit trickier than the above method. In this method, you can create your own
textbox using the TextBox class.
Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox, set the properties of the TextBox provided by the TextBox
class.
Property Description
Step 3 : And last add this textbox control to form using Add() method.
// Add this textbox to form
this.Controls.Add(Mytextbox);
Buttons:
A Button is an essential part of an application, or software, or webpage.
It allows the user to interact with the application or software.
It is typically represented by a clickable button on the screen that performs an action
when clicked by the user.
For example, if a user wants to exit from the current application so, he/she click the exit
button which closes the application.
It can be used to perform many actions like to submit, upload, download, etc. according
to the requirement of your program.
It can be available with different shape, size, color, etc. and you can reuse them in
different applications. In .NET Framework,
Button class is used to represent windows button control and it is inherited from
ButtonBase class. It is defined under System.Windows.Forms namespace.
In C# you can create a button on the windows form by using two different ways:
1. Design-Time:
It is the easiest method to create a button. Use the below steps:
Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are
allowed to place a Button control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Button control to set the
properties of the Button.
2. Run-Time:
It is a little bit trickier than the above method. In this method, you can create your own
Button using the Button class.
Step 1: Create a button using the Button() constructor is provided by the Button class.
// Creating Button using Button class
Button MyButton = new Button();
Step 2: After creating Button, set the properties of the Button provided by the Button class.
// Set the location of the button
Mybutton.Location = new Point(225, 198);
Step 3: And last add this button control to form using Add() method.
// Add this Button to form
this.Controls.Add(Mybutton);
Property Description
Group Boxes:
A GroupBox control is a container control that is used to place Windows Forms child
controls in a group.
The purpose of a GroupBox is to define user interfaces where we can categorize related
controls in a group.
In Windows form, GroupBox is a container which contains multiple controls on it and
the controls are related to each other.
Or in other words, GroupBox is a frame display around a group of controls with a
suitable optional title.
Or a GroupBox is used to categorize the related controls in a group.
The GroupBox class is used to represent the windows group box and also provide
different types of properties, methods, and events.
It is defined under System.Windows.Forms namespace.
The main use of a group box is to hold a logical group of RadioButton controls.
In C# you can create a GroupBox in the windows form by using two different ways:
1. Design-Time:
It is the easiest way to create a GroupBox as shown in the following steps:
Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the GroupBox from the toolbox on the form.
Step 3: After drag and drop you will go to the properties of the GroupBox to modify
GroupBox according to your requirements.
Output:
2. Run-Time:
It is a little bit trickier than the above method. In this method, you can create a GroupBox
programmatically with the help of syntax provided by the GroupBox class. The following
steps show how to set the create GroupBox dynamically:
Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox
class.
// Creating a GroupBox
Step 2: After creating GroupBox, set the property of the GroupBox provided by the
GroupBox class.
box.Name = "MyGroupbox";
Step 3: And last add this GroupBox control to the form and also add other controls on the
GroupBox using the following statements:
this.Controls.Add(box);
Types of Creating
1. Design Phase:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a
FlowLayoutPanel programmatically with the help of syntax provided by the
FlowLayoutPanel class. The following steps show how to set the create FlowLayoutPanel
dynamically:
// Creating a FlowLayoutPanel
Step 2: After creating a FlowLayoutPanel, set the property of the FlowLayoutPanel provided
by the FlowLayoutPanel class.
fl.Name = "Mycontainer";
fl.BorderStyle = BorderStyle.Fixed3D;
fl.ForeColor = Color.BlueViolet;
fl.Visible = true;
Step 3: And last add this FlowLayoutPanel control to the form and also add other controls
on the FlowLayoutPanel using the following statements:
// Adding a FlowLayoutPanel
this.Controls.Add(fl);
and
// to the FlowLayoutPanel
fl.Controls.Add(f1);
Constructor Description
FlowLayoutPanel() This Constructors is used to initialize a new instance of the
FlowLayoutPanel class.
Property Description
AutoScroll This property is used to get or set a value indicating whether the
container enables the user to scroll to any controls placed outside of its
visible boundaries.
AutoSize This property is used to get or set a value that indicates whether the
control resizes based on its contents.
AutoSizeMode This property indicates the automatic sizing behavior of the control.
BackColor This property is used to get or set the background color for the control.
BorderStyle This property indicates the border style for the control.
FlowDirectionThis property is used to get or set a value indicating the flow direction
of the FlowLayoutPanel control.
Font This property is used to get or set the font of the text displayed by the
control.
ForeColor This property is used to get or set the foreground color of the control.
Height This property is used to get or set the height of the control.
Location This property is used to get or set the coordinates of the upper-left
corner of the FlowLayoutPanel control relative to the upper-left corner
of its form.
Name This property is used to get or set the name of the control.
Padding This property is used to get or set padding within the control.
Size This property is used to get or set the height and width of the control.
Visible This property is used to get or set a value indicating whether the control
and all its child controls are displayed.
Width This property is used to get or set the width of the control.
WrapContents This property is used to get or set a value indicating whether the
FlowLayoutPanel control should wrap its contents or let the contents be
clipped.
Run-Time: It is a little bit trickier than the above method. In this method, you can create a
RadioButton programmatically with the help of the RadioButton class. The following steps
show how to create a RadioButton dynamically:
Step 1: Create a radio button using the RadioButton() constructor is provided by the
RadioButton class.
// Creating radio button
RadioButton r1 = new RadioButton();
Step 2: After creating RadioButton, set the properties of the RadioButton provided by the
RadioButton class.
// Set the AutoSize property
r1.AutoSize = true;
Properties of RadioButtons.
Property Description
This property is used to set the font of the text displayed by the
Font RadioButton control.
This property is used to set the foreground color of the
ForeColor RadioButton control.
Important Events
Event Description
Checkboxes:
The CheckBox control is the part of windows form which is used to take input from the
user. Or in other words,
CheckBox control allows us to select single or multiple elements from the given list or it
can provide us options like yes or no, true or false, etc.
It can be displayed as an image or text or both. The CheckBox is a class and defined
under System.Windows.Forms namespace.
In Windows form, you can create CheckBox in two different ways:
Design Time
2. Run Time:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can create
your own checkbox programmatically using the CheckBox class.
Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class.
// Creating checkbox
Step 2: After creating CheckBox, set the properties of the CheckBox provided by the
CheckBox class.
Mycheckbox.Height = 50;
// Set width of the checkbox
Mycheckbox.Width = 100;
Mycheckbox.Text = "Married";
Step 3: And last add this checkbox control to form using Add() method.
this.Controls.Add(Mycheckbox);
Property Description
Event Description
Tooltips:
In Windows Forms, the ToolTip represents a tiny pop-up box which appears when you
place your pointer or cursor on the control.
The purpose of this control is it provides a brief description about the control present in the
windows form.
The ToolTip class is used to create ToolTip control and also provide different types of
properties, methods, events and also provides run time status of the controls.
You are allowed to use a ToolTip class in any container or control. With the help of a single
ToolTip component, you are allowed to create multiple tooltips for multiple controls.
In C# you can create a ToolTip in the windows form by using two different ways:
1. Design-Time:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a
ToolTip control programmatically with the help of syntax provided by the ToolTip class.
The following steps show how to set the create ToolTip dynamically:
Step 1: Create a ToolTip control using the ToolTip() constructor is provided by the ToolTip
class.
// Creating a ToolTip control
ToolTip t_Tip = new ToolTip();
Step 2: After creating ToolTip control, set the property of the ToolTip control provided by
the ToolTip class.
// Setting the properties of ToolTip
t_Tip.Active = true;
t_Tip.AutoPopDelay = 4000;
t_Tip.InitialDelay = 600;
t_Tip.IsBalloon = true;
t_Tip.ToolTipIcon = ToolTipIcon.Info;
t_Tip.SetToolTip(box1, "Name should start with Capital letter");
t_Tip.SetToolTip(box2, "Password should be greater than 8 words")
Constructors.
Constructor Description
This Constructors is used to initialize a new instance of the ToolTip class with
ToolTip(IContainer) a specified container.
Properties
Property Description
This property is used to get or set a value indicating whether the ToolTip is
Active currently active.
AutomaticDelay This property is used to get or set the automatic delay for the ToolTip.
This property is used to get or set the period of time the ToolTip remains visible
AutoPopDelay if the pointer is stationary on a control with specified ToolTip text.
BackColor This property is used to get or set the background color for the control.
ForeColor This property is used to get or set the foreground color of the control.
This property is used to get or set the time that passes before the ToolTip
InitialDelay appears.
This property is used to get or set a value indicating whether the ToolTip should
IsBalloon use a balloon window.
This property is used to get or set the length of time that must transpire before
subsequent ToolTip windows appear as the pointer moves from one control to
ReshowDelay another.
This property is used to get or set a value that defines the type of icon to be
ToolTipIcon displayed alongside the ToolTip text.
ToolTipTitle This property is used to get or set a title for the ToolTip window.
Click
This event occurs when the mouse button is released, typically before the MouseUp event.
The handler for this event receives an argument of type EventArgs. Handle this event when
you only need to determine when a click occurs.
MouseClick
This event occurs when the user clicks the control with the mouse. The handler for this event
receives an argument of type MouseEventArgs. Handle this event when you need to get
information about the mouse when a click occurs.
DoubleClick
This event occurs when the control is double-clicked. The handler for this event receives an
argument of type EventArgs. Handle this event when you only need to determine when a
double-click occurs.
MouseDoubleClick
This event occurs when the user double-clicks the control with the mouse. The handler for
this event receives an argument of type MouseEventArgs. Handle this event when you need
to get information about the mouse when a double-click occurs.
MouseDown
This event occurs when the mouse pointer is over the control and the user presses a mouse
button. The handler for this event receives an argument of type MouseEventArgs.
MouseEnter
This event occurs when the mouse pointer enters the border or client area of the control,
depending on the type of control. The handler for this event receives an argument of type
EventArgs.
MouseHover
This event occurs when the mouse pointer stops and rests over the control. The handler for
this event receives an argument of type EventArgs.
MouseLeave
This event occurs when the mouse pointer leaves the border or client area of the control,
depending on the type of the control. The handler for this event receives an argument of
type EventArgs.
MouseMove
This event occurs when the mouse pointer moves while it is over a control. The handler for
this event receives an argument of type MouseEventArgs.
MouseUp
This event occurs when the mouse pointer is over the control and the user releases a mouse
button. The handler for this event receives an argument of type MouseEventArgs.
MouseWheel
This event occurs when the user rotates the mouse wheel while the control has focus. The
handler for this event receives an argument of type MouseEventArgs. You can use the Delta
property of MouseEventArgs to determine how far the mouse has scrolled.
Example:
You can handle various Mouse actions by using the events specified in the Control class.
Following listing shows how to handle a simple MouseUp Event:
using System;
using System.Windows.Forms;
using System.Drawing;
public class Mousedemo:Form
{
public Mousedemo()
{
this.MouseUp += new MouseEventHandler(OnMouseup);
}
public void OnMouseup(object sender,MouseEventArgs e)
{
this.Text = "Current Position (" +e.X + " , " + e.Y +")";
}
public static void Main()
{
Application.Run(new Mousedemo());
}
}
Keyboard Events:
KeyDown:
KeyPress:
The KeyPress event occurs when a key is pressed and generates a character.
It provides the character representation of the key that was pressed.
You can handle this event to process character input, such as validating or filtering user
input.
KeyUp:
The KeyUp event occurs when a key is released after being pressed down.
It provides the current state of the keyboard when the key was released.
You can handle this event to perform specific actions based on the key released.
To handle these keyboard events, you need to subscribe to them for the desired control or
form.
Here's an example demonstrating how to handle keyboard events for a Windows Forms
application:
using System;
using System.Windows.Forms;
Remember to instantiate and display an instance of the form to see the keyboard events in
action.
These keyboard events allow you to capture and respond to user input from the keyboard in
your C# application. You can customize the behavior based on the specific keys pressed or
released, enabling you to create interactive and responsive applications.
C# Menu control:
A Menu on a Windows Form is created with a MainMenu object, which is a collection of
MenuItem objects. MainMenu is the container for the Menu structure of the form and menus
are made of MenuItem objects that represent individual parts of a menu.
You can add menus to Windows Forms at design time by adding the MainMenu component
and then appending menu items to it using the Menu Designer.
After creating the Menu on the form , you have to double click on each menu item and write
the programs there depends on your requirements. The following C# program shows how
to show a messagebox when clicking a Menu item.
Example Program:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("You are selected MenuItem_1");
}
}
}
Some Members
CloneMenu () -- Sets this menu to be a similar copy of another menu.
MergeMenu () -- Merges an additional menus items with this one.
Some properties
Index -- Gets or sets the menu items position in its parent menu.
Checked -- Gets or sets a value representing whether a check mark appears nearby the text
of the menu item.
Text -- Gets or sets the text of the menu item.
Shortcut -- Gets or sets the shortcut key connected with the menu item.
Enabled -- Gets or sets a value representing whether the menu item is enabled.
In order to create C# MonthCalendar control, open the windows form application and
go to Toolbar appearing on the left side.
Find the MonthCalendar control, drag and drop it over the Form.
You can play with it and move it around over the Form with the help of mouse.
There is another way of creating the MonthCalendar control. Just double click on the
MonthCalendar control, it will automatically place the MonthCalendar control on the
Form.
Properties of Month Calendar Control.
Properties:
Properties Description
Events:
Events Description
ListBox control:
A control that displays a list of items that a user can select. This control can be populated
with items from a data source.
It allows the programmer to add items at design time by using the properties window or at
the runtime.
You can populate the list box items either from the properties window or at runtime.
To add items to a ListBox, select the ListBox control and get to the properties window,
for the properties of this control.
Click the ellipses (...) button next to the Items property.
This opens the String Collection Editor dialog box, where you can enter the values one at
a line.
The following are some of the commonly used properties of the ListBox control −
1
AllowSelection
Gets a value indicating whether the ListBox currently enables selection of list items.
2
BorderStyle
Gets or sets the type of border drawn around the list box.
3
ColumnWidth
4
HorizontalExtent
Gets or sets the value indicating whether a horizontal scrollbar is displayed in the list box.
6
ItemHeight
7
Items
8
MultiColumn
Gets or sets a value indicating whether the list box supports multiple columns.
9
ScrollAlwaysVisible
Gets or sets a value indicating whether the vertical scroll bar is shown at all times.
10
SelectedIndex
Gets or sets the zero-based index of the currently selected item in a list box.
11
SelectedIndices
Gets a collection that contains the zero-based indexes of all currently selected items in the list box.
12
SelectedItem
13
SelectedItems
Gets a collection containing the currently selected items in the list box.
14
SelectedValue
Gets or sets the value of the member property specified by the ValueMember property.
15
SelectionMode
Gets or sets the method in which items are selected in the list box. This property has values −
None
One
MultiSimple
MultiExtended
16
Sorted
Gets or sets a value indicating whether the items in the list box are sorted alphabetically.
17
Text
Gets or searches for the text of the currently selected item in the list box.
18
TopIndex
Gets or sets the index of the first visible item of a list box.
1 BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while items are
added to the ListBox one at a time.
2 ClearSelected
Unselects all items in the ListBox.
3 EndUpdate
Resumes drawing of a list box after it was turned off by the BeginUpdate method.
4 FindString
Finds the first item in the ListBox that starts with the string specified as an argument.
5 FindStringExact
Finds the first item in the ListBox that exactly matches the specified string.
6 GetSelected
Returns a value indicating whether the specified item is selected.
7 SetSelected
Selects or clears the selection for the specified item in a ListBox.
8 OnSelectedIndexChanged
Raises the SelectedIndexChanged event.
8 OnSelectedValueChanged
Raises the SelectedValueChanged event.
1 Click
Occurs when a list box is selected.
2 SelectedIndexChanged
Occurs when the SelectedIndex property of a list box is changed.
ComboBox control:
The ComboBox control is used to display a drop-down list of various items. It is a
combination of a text box in which the user enters an item and a drop-down list from
which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and
dropping it on the form.
You can populate the list box items either from the properties window or at runtime.
To add items to a ComboBox, select the ComboBox control and go to the properties
window for the properties of this control.
Click the ellipses (...) button next to the Items property. This opens the String
Collection Editor dialog box, where you can enter the values one at a line.
1 AllowSelection
Gets a value indicating whether the list enables selection of list items.
2 AutoCompleteCustomSource
Gets or sets a custom System.Collections .Specialized.StringCollection to use when
the AutoCompleteSourceproperty is set to CustomSource.
3 AutoCompleteMode
Gets or sets an option that controls how automatic completion works for the
ComboBox.
4 AutoCompleteSource
Gets or sets a value specifying the source of complete strings used for automatic
completion.
5 DataBindings
Gets the data bindings for the control.
6 DataManager
Gets the CurrencyManager associated with this control.
7 DataSource
Gets or sets the data source for this ComboBox.
8 DropDownHeight
Gets or sets the height in pixels of the drop-down portion of the ComboBox.
9 DropDownStyle
Gets or sets a value specifying the style of the combo box.
10 DropDownWidth
Gets or sets the width of the of the drop-down portion of a combo box.
11 DroppedDown
Gets or sets a value indicating whether the combo box is displaying its drop-down
portion.
12 FlatStyle
Gets or sets the appearance of the ComboBox.
13 ItemHeight
Gets or sets the height of an item in the combo box.
14 Items
Gets an object representing the collection of the items contained in this ComboBox.
15 MaxDropDownItems
Gets or sets the maximum number of items to be displayed in the drop-down part of
the combo box.
16 MaxLength
Gets or sets the maximum number of characters a user can enter in the editable area
of the combo box.
17 SelectedIndex
Gets or sets the index specifying the currently selected item.
18 SelectedItem
Gets or sets currently selected item in the ComboBox.
19 SelectedText
Gets or sets the text that is selected in the editable portion of a ComboBox.
20 SelectedValue
Gets or sets the value of the member property specified by the ValueMember
property.
21 SelectionLength
Gets or sets the number of characters selected in the editable portion of the combo
box.
22 SelectionStart
Gets or sets the starting index of text selected in the combo box.
23 Sorted
Gets or sets a value indicating whether the items in the combo box are sorted.
24 Text
Gets or sets the text associated with this control.
1 BeginUpdate
Prevents the control from drawing until the EndUpdate method is called, while
items are added to the combo box one at a time.
2 EndUpdate
Resumes drawing of a combo box, after it was turned off by the BeginUpdate
method.
3 FindString
Finds the first item in the combo box that starts with the string specified as an
argument.
4 FindStringExact
Finds the first item in the combo box that exactly matches the specified string.
5 SelectAll
Selects all the text in the editable area of the combo box.
1 DropDown
Occurs when the drop-down portion of a combo box is displayed.
2 DropDownClosed
Occurs when the drop-down portion of a combo box is no longer visible.
3 DropDownStyleChanged
Occurs when the DropDownStyle property of the ComboBox has changed.
4 SelectedIndexChanged
Occurs when the SelectedIndex property of a ComboBox control has changed.
5 SelectionChangeCommitted
Occurs when the selected item has changed and the change appears in the combo
box.
1 BackColor
Gets or sets the background color for the control.
2 BackgroundImage
Gets or set the background image for the TreeView control.
3 BackgroundImageLayout
Gets or sets the layout of the background image for the TreeView control.
4 BorderStyle
Gets or sets the border style of the tree view control.
5 CheckBoxes
Gets or sets a value indicating whether check boxes are displayed next to the tree
nodes in the tree view control.
6 DataBindings
Gets the data bindings for the control.
7 Font
Gets or sets the font of the text displayed by the control.
8 FontHeight
Gets or sets the height of the font of the control.
9 ForeColor
The current foreground color for this control, which is the color the control uses to
draw its text.
10 ItemHeight
Gets or sets the height of each tree node in the tree view control.
11 Nodes
Gets the collection of tree nodes that are assigned to the tree view control.
12 PathSeparator
Gets or sets the delimiter string that the tree node path uses.
13 RightToLeftLayout
Gets or sets a value that indicates whether the TreeView should be laid out from
right-to-left.
14 Scrollable
Gets or sets a value indicating whether the tree view control displays scroll bars
when they are needed.
15 SelectedImageIndex
Gets or sets the image list index value of the image that is displayed when a tree node
is selected.
16 SelectedImageKey
Gets or sets the key of the default image shown when a TreeNode is in a selected
state.
17 SelectedNode
Gets or sets the tree node that is currently selected in the tree view control.
18 ShowLines
Gets or sets a value indicating whether lines are drawn between tree nodes in the
tree view control.
19 ShowNodeToolTips
Gets or sets a value indicating ToolTips are shown when the mouse pointer hovers
over a TreeNode.
20 ShowPlusMinus
Gets or sets a value indicating whether plus-sign (+) and minus-sign (-) buttons are
displayed next to tree nodes that contain child tree nodes.
21 ShowRootLines
Gets or sets a value indicating whether lines are drawn between the tree nodes that
are at the root of the tree view.
22 Sorted
Gets or sets a value indicating whether the tree nodes in the tree view are sorted.
23 StateImageList
Gets or sets the image list that is used to indicate the state of the TreeView and its
nodes.
24 Text
Gets or sets the text of the TreeView.
25 TopNode
Gets or sets the first fully-visible tree node in the tree view control.
26 TreeViewNodeSorter
Gets or sets the implementation of IComparer to perform a custom sort of the
TreeView nodes.
27 VisibleCount
Gets the number of tree nodes that can be fully visible in the tree view control.
1 CollapseAll
Collapses all the nodes including all child nodes in the tree view control.
2 ExpandAll
Expands all the nodes.
3 GetNodeAt
Gets the node at the specified location.
4 GetNodeCount
Gets the number of tree nodes.
5 Sort
Sorts all the items in the tree view control.
6 ToString
Returns a string containing the name of the control.
Events of the TreeView Control
The following are some of the commonly used events of the TreeView control −
1 AfterCheck
Occurs after the tree node check box is checked.
2 AfterCollapse
Occurs after the tree node is collapsed.
3 AfterExpand
Occurs after the tree node is expanded.
4 AfterSelect
Occurs after the tree node is selected.
5 BeforeCheck
Occurs before the tree node check box is checked.
6 BeforeCollapse
Occurs before the tree node is collapsed.
7 BeforeExpand
Occurs before the tree node is expanded.
8 BeforeLabelEdit
Occurs before the tree node label text is edited.
9 BeforeSelect
Occurs before the tree node is selected.
10 ItemDrag
Occurs when the user begins dragging a node.
11 NodeMouseClick
Occurs when the user clicks a TreeNode with the mouse.
12 NodeMouseDoubleClick
Occurs when the user double-clicks a TreeNode with the mouse.
13 NodeMouseHover
Occurs when the mouse hovers over a TreeNode.
14 PaddingChanged
Occurs when the value of the Padding property changes.
15 Paint
Occurs when the TreeView is drawn.
16 RightToLeftLayoutChanged
Occurs when the value of the RightToLeftLayout property changes.
17 TextChanged
Occurs when the Text property changes.
ListView control:
The ListView control is used to display a list of items. Along with the TreeView
control, it allows you to create a Windows Explorer like interface.
Let's click on a ListView control from the Toolbox and place it on the form.
The ListView control displays a list of items along with icons. The Item property
of the ListView control allows you to add and remove items from it.
The SelectedItem property contains a collection of the selected items.
The MultiSelect property allows you to set select more than one item in the list
view.
The CheckBoxes property allows you to set check boxes next to the items.
1 Alignment
Gets or sets the alignment of items in the control.
2 AutoArrange
Gets or sets whether icons are automatically kept arranged.
3 BackColor
Gets or sets the background color.
4 CheckBoxes
Gets or sets a value indicating whether a check box appears next to each item in the
control.
5 CheckedIndices
Gets the indexes of the currently checked items in the control.
6 CheckedItems
Gets the currently checked items in the control.
7 Columns
Gets the collection of all column headers that appear in the control.
8 GridLines
Gets or sets a value indicating whether grid lines appear between the rows and
columns containing the items and subitems in the control.
9 HeaderStyle
Gets or sets the column header style.
10 HideSelection
Gets or sets a value indicating whether the selected item in the control remains
highlighted when the control loses focus.
11 HotTracking
Gets or sets a value indicating whether the text of an item or subitem has the
appearance of a hyperlink when the mouse pointer passes over it.
12 HoverSelection
Gets or sets a value indicating whether an item is automatically selected when the
mouse pointer remains over the item for a few seconds.
13 InsertionMark
Gets an object used to indicate the expected drop location when an item is dragged
within a ListView control.
14 Items
Gets a collection containing all items in the control.
15 LabelWrap
Gets or sets a value indicating whether item labels wrap when items are displayed in
the control as icons.
16 LargeImageList
Gets or sets the ImageList to use when displaying items as large icons in the control.
17 MultiSelect
Gets or sets a value indicating whether multiple items can be selected.
18 RightToLeftLayout
Gets or sets a value indicating whether the control is laid out from right to left.
19 Scrollable
Gets or sets a value indicating whether a scroll bar is added to the control when there
is not enough room to display all items.
20 SelectedIndices
Gets the indexes of the selected items in the control.
21 SelectedItems
Gets the items that are selected in the control.
22 ShowGroups
Gets or sets a value indicating whether items are displayed in groups.
23 ShowItemToolTips
Gets or sets a value indicating whether ToolTips are shown for the ListViewItem
objects contained in theListView.
24 SmallImageList
Gets or sets the ImageList to use when displaying items as small icons in the control.
25 Sorting
Gets or sets the sort order for items in the control.
26 StateImageList
Gets or sets the ImageList associated with application-defined states in the control.
27 TopItem
Gets or sets the first visible item in the control.
28 View
Gets or sets how items are displayed in the control. This property has the following
values:
29 VirtualListSize
Gets or sets the number of ListViewItem objects contained in the list when in virtual
mode.
30 VirtualMode
Gets or sets a value indicating whether you have provided your own data-
management operations for the ListView control.
Methods of the ListView Control
The following are some of the commonly used methods of the ListView control −
1 Clear
Removes all items from the ListView control.
1 ToString
Returns a string containing the string representation of the control.
1 ColumnClick
Occurs when a column header is clicked.
2 ItemCheck
Occurs when an item in the control is checked or unchecked.
3 SelectedIndexChanged
Occurs when the selected index is changed.
4 TextChanged
Occurs when the Text property is changed.
C# Tab control:
The TabControl manages tab pages where each page may host different child
controls. In this article, I will demonstrate how to create and use a TabControl in
Windows Forms.
Design time inclusion of Tab control:
To create a TabControl control at design-time, you simply drag and drop a
TabControl control from Toolbox onto a Form in Visual Studio. After you drag and
drop a TabControl on a Form, the TabControl1 is added to the Form and looks like
Figure 1.
A TabControl is just a container and has no value without tab pages. As you can see
from Figure 1, by default two Tab Pages are added to the TabControl. We can add
and remove tab pages by clicking on the Tasks handle and selecting Add and
Remove Tab links as you see in Figure 2.
1 Button
A control that responds to user input
2 Calendar
Represents a control that enables a user to select a date by using a visual
calendar display.
3 CheckBox
A control that a user can select or clear.
4 ComboBox
A drop-down list of items a user can select from.
5 ContextMenu
Gets or sets the context menu element that should appear whenever the
context menu is requested through user interface (UI) from within this
element.
6 DataGrid
Represents a control that displays data in a customizable grid.
7 DatePicker
A control that lets a user select a date.
8 Dialogs
An application may also display additional windows to help the user
gather or display important information.
9 GridView
A control that presents a collection of items in rows and columns that can
scroll horizontally.
10 Image
A control that presents an image.
11 Label
Displays text on a form. Provides support for access keys.
12 ListBox
A control that presents an inline list of items that the user can select from.
13 Menus
Represents a Windows menu control that enables you to hierarchically
organize elements associated with commands and event handlers.
14 PasswordBox
A control for entering passwords.
15 Popup
Displays content on top of existing content, within the bounds of the
application window.
16 ProgressBar
A control that indicates progress by displaying a bar.
17 RadioButton
A control that allows a user to select a single option from a group of
options.
18 ScrollViewer
A container control that lets the user pan and zoom its content.
19 Slider
A control that lets the user select from a range of values by moving a
Thumb control along a track.
20 TextBlock
A control that displays text.
21 ToggleButton
A button that can be toggled between 2 states.
22 ToolTip
A pop-up window that displays information for an element.
23 Window
The root window which provides minimize/maximize option, Title bar,
border and close button
WPF Architecture
The architecture of WPF can be classified into three layers,
Managed Layer
Unmanaged Layer
Managed Layer
This layer contains Presentation Framework and the Presentation Core, which is
basically part of .Net framework and written in managed code, hence called
managed layer. All the managed code management is managed by CLR itself.
Basically, three DLL files -PresentationFramework.dll, PresentationCode.dll, and
WindowsBase.dll build the make part of WPF Architecture.
On creating the WPF application, you will see these into the solution file.
PresentationFramework.dll
This DLL consists of all classes that are required to create the WPF UI. This wraps up
the controls, data bindings, styling, shapes, media, documents, annotations,
animation and more.
PresentationCore.dll
Presentation Core acts as a managed wrapper around MILCore and provides a
public interface for MIL. This is a low-level API exposed by WPF providing features
for 2D, 3D, geometry and so on. Presentation Core provides classes for creating
application visual tree. The Visual System creates a visual tree which contains
applications Visual Elements and rendering instructions. PresentationCore.dll is
responsible for this purpose.
WindowsBase.dll
WindowsBase.dll assembly holds the most basic and most important types in WPF
like DependencyObject, DependencyProperty, DispatcherObject and
DispatcherTimer.
These classes are the base of WPF. The main classes exist in System.Windows
namespace and System.Windows.Threading namespaces.
Unmanaged Layer
This layer has two segments.
MilCore
WindowsCodecs
This layer is also called MilCore (Media Integration Library).
MilCore (Media Integration Library)
Milcore is a part of the unmanaged code which allows tight integration with DirectX
(responsible for display and rendering). All rendering of controls in WPF is done
through DirectX engine. DirectX is a collection of API developed by Microsoft for
graphics, 2D, 3D programs.
WindowsCodecs
WindowsCodecs provides Imaging support in WPF. Image display, processing,
scaling and transform are all handled by WindowsCodecs
DirectX
DirectX is the low-level API through which WPF renders all graphics. DirectX talks
with drivers and renders the content.
User32
User32 actually manages memory and process separation. It is the primary core API
that every application uses. User32 decides which element will be placed where on
the screen.
GDI
GDI stands for Graphic Device Interface. GDI provides an expanded set of graphics
primitives and a number of improvements in rendering quality.
CLR
WPF leverages the full .NET Framework and executes on the Common Language
Runtime (CLR).
Device Drivers
Device Drivers are specific to the operating system. Device Drivers are used by the
applications to access low-level APIs.
Managed Layer
Unmanaged Layer
WindowsBase
PresentationFramework
PresentaionCore
1. WindowsBase: WindowsBase assembly defines the most basic and most
important types in WPF like DependencyObject, DependencyProperty,
DispatcherObject, DispatcherTimer.These classes are the base of WPF. The main
classes exists in System.Windows namespace and System.Windows.Threading
namespaces.
Advantages of WPF:
The ability to make very rich UIs relatively easily.
Easier animation and special effects
Inherent scalability
It uses current standard because it is newer
the developers of the controls will likely be more focused on WPF because it’s
XAML makes it easy to create and edit your UI and allows the development
work to be separated between a designer (XAML) and a programmer (C#).
Databinding is used to make a clean separation between data and layout.
Uses hardware efficiently for drawing the UI, for better performance.
It is used to make user interfaces for both Windows applications and web
applications.
Disadvantages :
* WPF's in-box control suite is far more limited than that of WinForms.
* There's greater support in the 3rd-party control space for WinForms. (That's
changing, but for now by advantage of time, WinForms has greater support in the
community).
* Most developers already know WinForms; WPF provides a new learning curve.
Under Templates, select Visual C# and in the middle panel, select WPF
Application.
Give the project a name. Type HelloWorld in the name field and click the OK
button.
By default, two files are created, one is the XAML file (mainwindow.xaml) and the
other one is the CS file (mainwindow.cs)
On mainwindow.xaml, you will see two sub-windows, one is the design window
and the other one is the source (XAML) window.
In WPF application, there are two ways to design an UI for your application. One
is to simply drag and drop UI elements from the toolbox to the Design Window.
The second way is to design your UI by writing XAML tags for UI elements. Visual
Studio handles XAML tags when drag and drop feature is used for UI designing.
In mainwindow.xaml file, the following XAML tags are written by default.
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
<Grid>
</Grid>
</Window>
When you look at the source window, you will see that Visual Studio has
generated the XAML code of the TextBlock for you.
Let’s change the Text property of TextBlock in XAML code from TextBlock to
Hello World.
<Grid>
<TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
Margin = "235,143,0,0" TextWrapping = "Wrap" Text = "Hello World!"
VerticalAlignment = "Top" Height = "44" Width = "102" />
</Grid>
</Window>
• Now, you will see the change on the Design Window as well.
When the above code is compiled and executed, you will see the following window.
Congratulations! You have designed and created your first WPF application.
In XAML, it very easy to create, initialize, and set properties of objects with
hierarchical relations.
It is mainly used for designing GUIs, however it can be used for other purposes as
well, e.g., to declare workflow in Workflow Foundation.
Contents of XAML:
Basic Syntax
When you create your new WPF project, you will encounter some of the XAML code
by default in MainWindow.xaml as shown below.
Information Description
It is because in XML, the value of the attributes must be a string while in XAML, it
can be a different object which is known as Property element syntax.
The syntax of an Object element starts with a left angle bracket (<) followed by the
name of an object, e.g. Button.
Define some Properties and attributes of that object element.
The Object element must be closed by a forward slash (/) followed immediately by a
right angle bracket (>).
<Button.Content>Click Me</Button.Content>
<Button.Height>30</Button.Height>
<Button.Width>60</Button.Width>
</Button>
</StackPanel>
They are in fact separable pieces of technology. To understand how that can be, let's
look at a
<StackPanel>
<Button x:Name = "button" Content = "Click Me" HorizontalAlignment = "Left"
Margin = "150" VerticalAlignment = "Top" Width = "75" />
</StackPanel>
In case you choose not to use XAML in WPF, then you can achieve the same GUI
result with procedural language as well. Let’s have a look at the same example, but
this time, we will create a button in C#.
using System.Windows;
using System.Windows.Controls;
namespace WPFXAMLOverview {
/// <summary>
InitializeComponent();
this.Content = stackPanel;
button.HorizontalAlignment = HorizontalAlignment.Left;
button.Margin = new Thickness(150);
button.VerticalAlignment = VerticalAlignment.Top;
button.Width = 75;
stackPanel.Children.Add(button);
}
When you compile and execute either the XAML code or the C# code, you will see
the same output as shown below.
From the above example, it is clear that what you can do in XAML to create,
initialize, and set properties of objects, the same tasks can also be done using code.
Data binding and static resources are markup extensions. There are some predefined
XAML markup extensions in System.xaml which can be used.