C# With Winforms
C# With Winforms
Using C#
Student Guide
Revision 4.0
Student Guide
Information in this document is subject to change without notice. Companies, names and data
used in examples herein are fictitious unless otherwise noted. No part of this document may be
reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Object Innovations.
Product and company names mentioned herein are the trademarks or registered trademarks of
their respective owners.
Rev. 4.0
ii
Chapter 2
Chapter 3
Using Controls
Chapter 4
List Controls
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Resources
Chapter 10
Chapter 11
Data Access
Chapter 12
Data Binding
Chapter 13
Appendix A
Learning Resources
Rev. 4.0
iii
Directory Structure
The course software installs to the root directory
C:\OIC\WinCs.
Example programs for each chapter are in named
subdirectories of chapter directories Chap01, Chap02, and
so on.
The Labs directory contains one subdirectory for each lab,
named after the lab number. Starter code is frequently
supplied, and answers are provided in the chapter directories.
The Demos directory is provided for hand-on work during
lectures.
The Deploy directory is provided to test deployment.
Rev. 4.0
iv
Lab 3A (Optional)......................................................................................................... 69
Making Selections......................................................................................................... 70
Using the CheckBox ..................................................................................................... 71
Example: Using the CheckBox..................................................................................... 72
Using the RadioButton with a GroupBox..................................................................... 74
Example: Using a Radio Button .................................................................................. 76
Working with Ranges ................................................................................................... 78
Using the NumericUpDown ......................................................................................... 79
Example: Using the NumericUpDown ........................................................................ 80
Using the TrackBar ....................................................................................................... 81
Example: Using the TrackBar...................................................................................... 82
Using the ProgressBar .................................................................................................. 83
Example: Using the ProgressBar ................................................................................. 84
Working with Dates ...................................................................................................... 86
Using the MonthCalendar ............................................................................................. 87
Using DateTimePicker.................................................................................................. 90
Example: Using the DateTimePicker........................................................................... 91
Other Controls............................................................................................................... 94
Tracing .......................................................................................................................... 95
Debug and Trace Classes .............................................................................................. 96
Tracing Example........................................................................................................... 97
Viewing Trace Output .................................................................................................. 98
Debug Statements ......................................................................................................... 99
Debug Output.............................................................................................................. 100
WriteLine Syntax ........................................................................................................ 101
Lab 3B......................................................................................................................... 102
Summary ..................................................................................................................... 103
Chapter 4 List Controls.............................................................................................. 107
Working with Lists ..................................................................................................... 109
Using a ListBox .......................................................................................................... 110
Selected Items ............................................................................................................. 111
Selected Indices .......................................................................................................... 112
Other ListBox Features ............................................................................................... 113
Adding and Removing Items Dynamically................................................................. 115
Example: Using a ListBox .......................................................................................... 116
Using the ComboBox.................................................................................................. 119
ComboBox Example ................................................................................................... 120
Storing Objects in List Controls ................................................................................. 122
Lab 4A ........................................................................................................................ 123
Using the DomainUpDown Control ........................................................................... 124
Example: Using the DomainUpDown ........................................................................ 125
Using a ListView ........................................................................................................ 127
Adding Columns to a ListView .................................................................................. 129
Adding Items to a ListView........................................................................................ 130
Example: Using a ListView ........................................................................................ 132
Rev. 4.0
vi
vii
viii
ix
xi
Rev. 4.0
xii
WinCs
Chapter 2
Chapter 2
Rev. 4.0
41
WinCs
Chapter 2
Rev. 4.0
42
WinCs
Chapter 2
Visual Studio
Visual Studio, which we used in the first chapter to
create and run simple projects, is extremely useful in
developing Windows applications.
Visual Studio allows us to design forms using a dragdrop interface.
If you are familiar with the IDEs in Visual Basic or Visual
C++, the Visual Studio IDE will look very familiar!
Rev. 4.0
43
WinCs
Chapter 2
Rev. 4.0
44
WinCs
Chapter 2
Rev. 4.0
Alphabetically:
45
WinCs
Chapter 2
You can add the "default" event handler for each control by
double-clicking the control in design view.
Rev. 4.0
46
WinCs
Chapter 2
Rev. 4.0
47
WinCs
Chapter 2
Rev. 4.0
48
WinCs
Chapter 2
5. We want to make sure the following property values are set for
the button and form:
Object
Name Property
Text Property
Button
Form
btnCheer
MainForm
Cheer!
NFL Football
Rev. 4.0
49
WinCs
Chapter 2
Rev. 4.0
50
WinCs
Chapter 2
Rev. 4.0
51
WinCs
Chapter 2
Rev. 4.0
52
WinCs
Chapter 2
Rev. 4.0
53
WinCs
Chapter 2
Rev. 4.0
54
WinCs
Chapter 2
55
WinCs
Chapter 2
Rev. 4.0
56
WinCs
Chapter 2
Rev. 4.0
57
WinCs
Chapter 2
Rev. 4.0
58
WinCs
Chapter 2
Lab 2
My Calculator
In this lab you will you will use Visual Studio and the Forms
Designer to build a simple calculator that performs addition,
subtraction, multiplication and division on floating point numbers.
Rev. 4.0
59
WinCs
Chapter 2
Summary
Visual Studio makes it easy for programmers to build
Windows Forms applications.
The Forms Designer allows programmers to drag
controls from a toolbox and visually place them on a
form.
The Properties Window can be used to specify values
for form and control properties.
The Forms Designer generates code based on the
programmer's drag-drop actions and property
settings.
C# and the tools inside Visual Studio make it easy to
build Windows Forms applications that look nice and
are easy to use.
Rev. 4.0
60
WinCs
Chapter 2
Lab 2
My Calculator
Introduction
In this lab you will you will use Visual Studio and the Forms Designer to build a simple
calculator that performs addition, subtraction, multiplication and division on floating
point numbers. Your form should resemble the following:
You will need to use exception handling to make sure that "garbage" data in the operand
1 and/or operand 2 textbox does not cause your program to "crash".
Suggested Time:
30 minutes
Root Directory:
OIC\WinCs
Directories:
Labs\Lab2
OIC\Data\Graphics
Chap02\MyCalculator
Instructions
1. Create a new C# Windows Forms Application named MyCalculator. Name the form
class and the associated file Calculator. Save the solution.
2. Design the form similar to that shown above.
3. Copy the icon files for the four arithmetic operations, MISC18.ICO, MISC19.ICO,
MISC20.ICO and MISC21.ICO, from OIC\Data\Graphics to the working directory.
Rev. 4.0
61
WinCs
Chapter 2
Property
Value
Label
Name
Text
lblOperand1
Operand 1:
TextBox
Name
Text
TextAlign
txtOperand1
(blank)
Right
Label
Name
Text
lblOperand2
Operand 2:
TextBox
Name
Text
TextAlign
txtOperand2
(blank)
Right
Button
Name
Text
Image
btnAdd
(blank)
MISC18.ICO
Button
Name
Text
Image
btnSubtract
(blank)
MISC19.ICO
Button
Name
Text
Image
btnMultiply
(blank)
MISC20.ICO
Button
Name
Text
Image
btnDivide
(blank)
MISC21.ICO
Label
Name
Text
lblAnswer
Answer:
TextBox
Name
Text
TextAlign
txtAnswer
(blank)
Right
5. Trap the Click event for each of the four buttons that specify math operations.
6. In each handler, write code to convert the string data in each textbox to a floating
point value. Perform the appropriate math operation for the button. Finally, place the
result back in the textbox that holds the answer. Compile and run the program.
Rev. 4.0
62
WinCs
Chapter 10
Chapter 10
Rev. 4.0
359
WinCs
Chapter 10
Rev. 4.0
360
WinCs
Chapter 10
Rev. 4.0
361
WinCs
Chapter 10
Rev. 4.0
362
WinCs
Chapter 10
Rev. 4.0
363
WinCs
Chapter 10
Application Events
The Application class fires several events:
The ApplicationExit event fires after all forms have closed
and the application is about to terminate.
The Idle event fires when the application is entering the idle
state. This occurs after the application has processed all
messages in the input queue.
The ThreadExit event fires when a thread is about to
terminate. It fires before the ApplicationExit event.
The ThreadException event fires when an unhandled
exception occurs. It can be used to allow the application to
continue executing.
364
WinCs
Chapter 10
Logging to a File
In running our little example program, we may be
unsure whether the OnExit event handler was
actually called, because the message box was not
displayed.
There are some subtleties in Windows that may prevent a
window from being displayed too late in the application shut
down process.
The log file log.txt for the simple run shows that the
event handler was indeed called.
Rev. 4.0
365
WinCs
Chapter 10
Closing a Window
As mentioned earlier, you should normally shut down
an application more gracefully by closing its main
window.
This is illustrated by the Close button in our example.
private void btnClose_Click(object sender,
EventArgs e)
{
Log.WriteLine("Close clicked");
Close();
}
Rev. 4.0
366
WinCs
Chapter 10
Rev. 4.0
367
WinCs
Chapter 10
Rev. 4.0
368
WinCs
Chapter 10
Filtering Messages
.NET allows Windows Forms programmers to add a
message filter to the application message pump to
monitor Windows messages.
You should be quite familiar with Windows SDK
programming before attempting this.
Rev. 4.0
369
WinCs
Chapter 10
Rev. 4.0
370
WinCs
Chapter 10
Rev. 4.0
371
WinCs
Chapter 10
Configuration Files
Configuration files are XML files that provide
configuration parameters to applications.
They can be changed without having to recompile the
application.
Rev. 4.0
372
WinCs
Chapter 10
Rev. 4.0
373
WinCs
Chapter 10
The ConfigurationManager class supersedes the ConfigurationSettings class, which is now obsolete.
Rev. 4.0
374
WinCs
Chapter 10
375
WinCs
Chapter 10
Rev. 4.0
376
WinCs
Chapter 10
Rev. 4.0
377
WinCs
Chapter 10
Application Settings
The .NET Framework has always provided the
capability to store application settings as an XML
fragment in a configuration file.
Before .NET 2.0, configuration setting information pertained
only to the application as a whole (not individual users) and
was read-only.
Rev. 4.0
378
WinCs
Chapter 10
Rev. 4.0
379
WinCs
Chapter 10
Try changing the font and title. Exit the application and run
again. You should see the changes preserved.
Now restore the defaults. Again, exit the application and run
again.
Rev. 4.0
380
WinCs
Chapter 10
5. Build and run. Try changing the font. Note that the size of the
buttons change size to harmonize with the size of the font. Note
that if you run the application again, any changes you made to
the font will not be preserved.
Rev. 4.0
381
WinCs
Chapter 10
7. Click the Ellipsis button . Select Font in the left-hand list, and
click the drop-down arrow on the right side.
382
WinCs
Chapter 10
10. Click OK and OK. You should now see the new default font
size reflected by the Form Designer. In Solution Explorer there
will also be new files Settings.Designer.cs and app.config.
Rev. 4.0
383
WinCs
Chapter 10
14. Build and run. The new font will now be persisted.
Rev. 4.0
384
WinCs
Chapter 10
385
WinCs
Chapter 10
Rev. 4.0
386
WinCs
Chapter 10
System;
System.Collections.Generic;
System.Text;
System.Configuration;
namespace DemoSettings
{
class ManualSettings : ApplicationSettingsBase
{
[UserScopedSetting()]
[DefaultSettingValue("Default Title")]
public string TitleSetting
{
get
{
return (string) this["TitleSetting"];
}
set
{
this["TitleSetting"] = value;
}
}
}
}
Rev. 4.0
387
WinCs
Chapter 10
Rev. 4.0
388
WinCs
Chapter 10
4. Set the following properties of the new form and buttons that
are normal for model dialogs:
a. FormBorderStyle is FixedDialog
b. No control box, minimize box, or maximize box.
c. The OK button should have DialogResult OK, and the
cancel button DialogResult of Cancel.
5. Add a handler for clicking the Change Title button.
Rev. 4.0
389
WinCs
Chapter 10
7. Add code to the handler of the Load event to load the setting for
the title and use it to initialize the title of the form.
Settings set = Settings.Default;
set.Reload();
ManualSettings ms = new ManualSettings();
ms.Reload();
this.Text = (string)ms.TitleSetting;
8. Build and run. You should now be able to change both the font
and the title, and have these values persisted. You may examine
the user.config file.
Rev. 4.0
390
WinCs
Chapter 10
11. Build and run. Change the values of the font and the title.
Now click the Restore Defaults button, and observe that the
values stored in the application configuration file are used.
Rev. 4.0
391
WinCs
Chapter 10
Rev. 4.0
392
WinCs
Chapter 10
Rev. 4.0
393
WinCs
Chapter 10
Rev. 4.0
394
WinCs
Chapter 10
Rev. 4.0
395
WinCs
Chapter 10
Lab 10
Checking Your System
In this lab, you will use a config file to specify a set of application
ProgIDs that should be loaded into a listbox. The program will
allow the user to select a ProgID from the listbox and check to see
if the corresponding application is loaded on the system.
Rev. 4.0
396
WinCs
Chapter 10
Summary
The Application class represents the class that
manages a Windows Forms application.
It contains methods to start and stop a Windows Forms
application.
Rev. 4.0
397
WinCs
Chapter 10
Lab 10
Checking Your System
Introduction
In this lab, you will use a config file to specify a set of application ProgIDs that should be
loaded into a listbox. The program will allow the user to select a ProgID from the listbox
and check to see if the corresponding application is loaded on the system.
Suggested Time:
45 minutes
Root Directory:
OIC\WinCs
Directories:
Labs\Lab10\CheckingYourSystem
Chap10\CheckingYourSystem
Instructions
1. Create a new Windows Forms Application named CheckingYourSystem. Name the
form class and the associated file MainForm.
2. Build a config file that resembles the following. Name the file App.config, save it in
the source directory, and add it to your Visual Studio project.
<configuration>
<appSettings>
<add key="Count" value="3" />
<add key="App1" value="Word.Application" />
<add key="App2" value="Excel.Application" />
<add key="App3" value="MemStick.MSAThumbnail" />
Rev. 4.0
398
WinCs
Chapter 10
</appSettings>
</configuration>
5. Write code in the Click event of your Check button to use the ProgID of the selected
listbox item and test to see if it is listed in the registry as an installed application. If it is,
it will be listed under the HKEY_CLASSES_ROOT hive.
private void btnCheckSelected_Click(object sender, EventArgs e)
{
// Get a reference to HKEY_CLASSES_ROOT
RegistryKey hive = Registry.ClassesRoot;
// Get the ProgID from the listbox
string progID = "";
try
{
progID = lstApplications.SelectedItem.ToString();
if (progID == "") return;
}
catch
{
return;
}
// Lookup the ProgID
RegistryKey key = hive.OpenSubKey(progID);
if (key != null)
{
string msg = progID + " is installed";
MessageBox.Show(msg, "Intallation", MessageBoxButtons.OK,
MessageBoxIcon.Information);
key.Close();
}
else
{
string msg = progID + " is NOT installed";
Rev. 4.0
399