0% found this document useful (0 votes)
19 views

Cse8 ch02

It is second chapter of the book

Uploaded by

shallumanning
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Cse8 ch02

It is second chapter of the book

Uploaded by

shallumanning
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

TRAINING & REFERENCE

murach’s
C# 8th Edition

(Chapter 2)

Thanks for downloading this chapter from Murach’s C# (8th Edition). We hope it
will show you how easy it is to learn from any Murach book, with its paired-pages
presentation, its “how-to” headings, its practical coding examples, and its clear, concise
style.
To view the full table of contents for this book, you can go to our website. From there,
you can read more about this book, you can find out about any additional downloads that
are available, and you can review our other books on related topics.
Thanks for your interest in our books!

Mike Murach & Associates, Inc.


1-800-221-5528 • (559) 440-9071 • Fax: (559) 440-0963
[email protected] • www.murach.com
Copyright © 2023 Mike Murach & Associates. All rights reserved.
What C# developers have said about previous editions
“I personally think that Microsoft should just hand over all documentation
for their technologies to Murach! You make it fun, intuitive, and interesting to
learn.”
Joanne Wood, C# Web Developer, Rhode Island

“I am actually flying through the C# book! And a lot of the topics I had
problems with in the past are now making perfect sense in this book.”
Jim Bonner, Test Lab Engineer, Washington

“In 20+ years of software development, I have never read another book so
well organized. Topics flow in a well-thought-out, logical order and are easy to
follow and understand. When I need new technical books in the future, I will
always search for a Murach book first.”
Jeff Rumage, Lower Alabama .NET User Group

“Best C# book ever, precise and to the point, with lots and lots of examples.
Highly recommended for beginners.”
Posted at an online bookseller

“Murach has yet again hit a home run! This book gets you from zero to Jr Dev
knowledge in no time.”
Brian Knight, Founder, Pragmatic Works, Florida

“I have to tell you that your C# book is far and away the best resource I have
seen to date. It is simple, straightforward, presents logical examples, and the
two-page format is the best.”
Timothy Layton, Developer, Missouri

“I have learned more in the 800+ pages of this book than I have reading half a
dozen other books and hours of forum posts online.”
Posted at an online bookseller
2
How to design a Windows
Forms app
In the last chapter, you learned the basic skills for working with Visual Studio,
you toured a Windows Forms app, and you tested an app with three Windows
forms. Now, in this chapter, you’ll learn how to use Visual Studio to design the
user interface for a Windows Forms app.

How to get started.................................................................34


How to create a new project...........................................................................34
How to configure a new Windows Forms app................................................36
How to design a form............................................................38
The design of the Invoice Total form.............................................................38
How to add controls to a form....................................................................... 40
How to set properties......................................................................................42
Common properties for forms and controls.................................................. 44
How to add navigation features..................................................................... 46
The property settings for the Invoice Total form...........................................48
How to finish your design.....................................................50
How to rename the files of a project...............................................................50
How to save the files of a project....................................................................50
Perspective............................................................................52
34 Section 1 An introduction to Visual Studio

How to get started


This chapter starts by showing how to create and configure a new Windows
Forms app. Once you do that, you can design the form by adding controls and
setting properties.

How to create a new project


To create a Windows Forms app, you start by creating a new project as
shown in figure 2-1. When creating a new project, Visual Studio provides several
templates that you can use. To create a Windows Forms app using .NET, for
example, you select the Windows Forms App template. Among other things, this
template includes dependencies for all the features you’re most likely to use as
you develop a Windows app.
Note that you can select a template from the list at the right side of this
dialog as shown here. You can also filter this list using the drop-down lists at the
top of this dialog to make it easier to find the template you want. You can select
a template from the list of recent project templates at the left side of the window.
Or you can search for a template using the search text box.
This figure also shows how to change what’s displayed when Visual Studio
starts and the development settings that Visual uses. If you don’t want the Start
window to be displayed when Visual Studio starts, for example, you can change
the startup option. Similarly, if you want the Visual Studio menus to appear as
shown in this book, you can change the development settings option to “Visual
C#”.
Chapter 2 How to design a Windows Forms app 35

The dialog that displays the project templates

How to create a new C# project


1. Click the Create a New Project button in the Start window, or use the
FileNewProject command to open the Create a New Project dialog.
2. Choose the Windows Forms App template from the list at the right side of the
dialog, or choose a recently used template from the left side of the dialog.
3. Click the Next button to display the Configure Your New Project dialog shown in
the next figure.

How to change the startup and development settings options


•• If you don’t want the Start window to be displayed when you start Visual Studio or
when you close a solution, you can select the ToolsOptions command, select the
General category under the Environment group, and select an option from the “On
startup, open” drop-down list. The other options are “Most recent solution” and
“Empty environment”.
•• If your menus don’t appear as shown in this book, you can change the development
settings using the ToolsImport and Export Settings command to start the Settings
Wizard. Then, choose the “Reset all settings” option, the “Yes, save my current
settings” option, and the “Visual C#” option as you step through the wizard.

Description
•• The project template that you select determines the initial files, dependencies, code,
and property settings that are added to the project.

Figure 2-1 How to create a new project


36 Section 1 An introduction to Visual Studio

How to configure a new Windows Forms app


When you click the Next button from the dialog in figure 2-1, the first dialog
in figure 2-2 is displayed. Then, you can use this dialog to specify the name for
the project and the folder (location) where it will be stored. The location defaults
to the last location where you created a project.
If you want to change the location for a project, you can click the Browse
button to select a different location; display the Location drop-down list to select
a location you’ve used recently; or type a path directly. If you specify a path that
doesn’t exist, Visual Studio will create the necessary folders for you.
Visual Studio automatically creates a new folder for the project at the speci-
fied location using the project name you specify. In the window in this figure, for
example, InvoiceTotal is the project name and C:\C# is the location. By default,
Visual Studio also creates a new folder for the solution using the same name as
the project. As a result, Visual Studio will create one folder for the solution, and
a subfolder for the project.
If a solution will contain a single project, though, you may want to store
the project and solution in the same folder. To do that, you can select the “Place
solution and project in the same directory” check box. Then, the solution is given
the same name as the project. In the apps for this book, the project and solution
files are typically stored in separate folders even though most solutions contain a
single project.
Incidentally, the terms folder and directory are used as synonyms throughout
this book. Although Microsoft started referring to directories as folders some
time ago, most of the Visual Studio documentation still uses the term directory.
That’s why this book uses whichever term seems more appropriate at the time.
When you click the Next button from this dialog, the second dialog in this
figure is displayed. This dialog lets you choose the framework version you want
to use for the app. In this figure, .NET 7.0 (Standard Term Support) is selected.
This is the version that supports C# 11.
Chapter 2 How to design a Windows Forms app 37

The dialogs for configuring a new Windows Forms app

How to configure a new Windows Forms app


1. Enter a name for the project, which will enter the same name for the solution.
2. Enter the location (folder) for the project (and solution). To do that, you can click
the Browse […] button.
3. Edit the solution name if necessary, then click the Next button to display the
Additional Information dialog.
4. Select the framework you want to use for the app, then click the Create button to
create the new project.

Description
•• Visual Studio remembers the location you specify when you create a new project
and uses it as the default location the next time you create a project.
•• If the “Place solution and project in the same directory” box is checked, Visual Studio
stores the solution and project files in the same folder. Otherwise, it creates a folder for
the solution and a subfolder for the project.

Figure 2-2 How to configure a new Windows Forms app


38 Section 1 An introduction to Visual Studio

How to design a form


When you create a new project, the project begins with a single, blank form.
You can then add controls to this form and set the properties of the form and
controls so they look and work the way you want.

The design of the Invoice Total form


Figure 2-3 presents the Invoice Total form that this chapter shows you how
to design. As you can see, this form consists of ten controls: four text boxes, four
labels, and two buttons.
The Invoice Total form lets the user enter a subtotal into the first text box,
and then calculates the discount percent, discount amount, and total for that
invoice when the user clicks the Calculate button. For this simple application, the
discount percent is based upon the amount of the subtotal, and the results of the
calculation are displayed in read-only text box controls.
After the results of the calculation are displayed, the user can enter a
different subtotal and click the Calculate button again to perform another calcu-
lation. This cycle continues until the user clicks the Close button in the upper
right corner of the form or clicks the Exit button. Then, the form is closed and
the application ends.
This application also provides keystroke options for users who prefer using
the keyboard to the mouse. In particular, the user can activate the Calculate
button by pressing the Enter key and the Exit button by pressing the Esc key. The
user can also activate the Calculate button by pressing Alt+C and the Exit button
by pressing Alt+X.
In the topics that follow, you’ll learn how to use the Form Designer to design
the form shown here. As you do that, Visual Studio automatically generates the
C# code that’s needed to define the form and its controls. In other words, the
form that you see in the Form Designer is just a visual representation of the form
that the C# code is going to display later on. Then, all you have to do is write the
C# code that gives the form its functionality, and you’ll learn how to do that in
the next chapter.
Chapter 2 How to design a Windows Forms app 39

The Invoice Total form

Text box

Labels
Read-only
text boxes

Buttons

Description
•• A text box is used to get the subtotal from the user. Read-only text boxes are used
to display the discount percent, discount amount, and total. And label controls are
used to identify the values that are in the text boxes on the form.
•• After entering a subtotal, the user can click the Calculate button to calculate the
discount percent, discount amount, and total. Alternatively, the user can press the
Enter key to perform the calculation.
•• To calculate another invoice total, the user can enter another subtotal and then click
the Calculate button or press the Enter key again.
•• To close the form and end the application, the user can click the Close button in the
upper right corner of the form or click the Exit button. Alternatively, the user can
press the Esc key to exit from the form.
•• The user can press Alt+C to activate the Calculate button or Alt+X to activate the
Exit button. On most systems, the letters that activate these buttons aren’t under-
lined until the user presses the Alt key.

Three types of controls


•• A label displays text on a form.
•• A text box lets the user enter text on a form.
•• A button initiates form processing when clicked.

Figure 2-3 The design of the Invoice Total form


40 Section 1 An introduction to Visual Studio

How to add controls to a form


Figure 2-4 shows how you can use the Toolbox to add controls to a form.
The easiest way to do that is to drag the control from the Toolbox to the form.
Then, the control is placed wherever you drop it, and it’s given its default size. In
this figure, for example, the button control is being dragged from the Toolbox to
the form.
Once you add a control to a form, you can resize the control by selecting it
and dragging one of its handles, and you can move the control by dragging the
control to a new location on the form. If you prefer, you can place and size the
control in a single operation by clicking the control in the Toolbox, then clicking
and dragging in the form.
A second way to add a control is to click on the control in the Toolbox
and then click the form at the location where you want to add the control. This
creates the control at its default size. You can also size the control as you add it
by dragging on the form.
A third method for adding controls is to double-click the control you want to
add in the Toolbox. This places the control in the upper left corner of the form at
its default size. You can then move and resize the control.
If the AutoHide feature is activated for the Toolbox and you click on the
Toolbox tab to display it, the display frequently obscures some or all of the form.
This makes it difficult to add controls. As a result, it’s a good idea to turn off the
AutoHide feature when you’re adding controls. To do that, just click the pushpin
button in the upper right corner of the Toolbox.
After you have added controls to the form, you can work with several
controls at once. For example, suppose you have four text box controls on your
form and you want to make them all the same size with the same alignment. To
do that, first select all four controls by holding down the Ctrl or Shift key as you
click on them or by using the mouse pointer to drag a dotted rectangular line
around the controls. Then, use the commands in the Format menu or the buttons
in the Layout toolbar to move, size, and align the controls relative to the primary
control. If you select the controls one at a time, the primary control will be the
first control you select. If you select the controls by dragging around them, the
primary control will be the last control in the group. To change the primary
control, just click on it. (The primary control will have different color handles so
you can identify it.)
Although these techniques may be hard to visualize as you read about them,
you’ll find that they’re relatively easy to use. All you need is a little practice,
which you’ll get in the exercise for this chapter.
Chapter 2 How to design a Windows Forms app 41

A form after some controls have been added to it

Control that’s
selected in
the Toolbox

Control that’s Sizing


being added handle
to the form

Three ways to add a control to a form


•• Select the control in the Toolbox. Then, click in the form where you want to place
the control. Or, drag the pointer on the form to place the control and size it at the
same time.
•• Double-click the control in the Toolbox. Then, the control is placed in the upper left
corner of the form.
•• Drag the control from the Toolbox and drop it on the form. Then, the control is
placed wherever you drop it.

How to select and work with controls


•• To select a control on the form, click it.
•• To move a control, drag it.
•• To size a selected control, drag one of its handles. Note, however, that you can’t size
a label by dragging its handles unless you change its AutoSize property to False.
•• To select more than one control, hold down the Shift or Ctrl key as you click on
each control. You can also select a group of controls by clicking on a blank spot in
the form and then dragging around the controls.
•• To align, size, or space a group of selected controls, click on a control to make it
the primary control. Then, use the commands in the Format menu or the buttons
on the Layout toolbar to align, size, or space the controls relative to the primary
control.
•• You can also size all of the controls in a group by sizing the primary control in the
group. And you can drag any of the selected controls to move all the controls.
•• To change the size of a form, click the form and drag one of its sizing handles.

Figure 2-4 How to add controls to a form


42 Section 1 An introduction to Visual Studio

How to set properties


After you have placed controls on a form, you need to set each control’s
properties. These are the values that determine how the controls will look and
work when the form is displayed. In addition, you need to set some of the
properties for the form itself.
To set the properties of a form or control, you work with the Properties
window as shown in figure 2-5. To display the properties for a specific control,
click on it in the Form Designer window to select the control. To display the
properties for the form, click the form’s title bar or any blank area of the form.
In the Properties window, you can select a property by clicking it. When you
do, a brief description of that property is given at the bottom of the Properties
window. (If you can’t see this description, you can drag the bottom line of the
window upward.) Then, to change a property setting, you change the entry to the
right of the property name by typing a new value or choosing a new value from a
drop-down list.
To display properties alphabetically or by category, you can click the
appropriate button at the top of the Properties window. At first, you may want
to display the properties by category so you have an idea of what the different
properties do. Once you become more familiar with the properties, though,
you may be able to find the ones you’re looking for faster if you display them
alphabetically.
As you work with properties, you’ll find that most are set the way you want
by default. In addition, some properties such as Height and Width are set inter-
actively as you size and position the form and its controls in the Form Designer
window. As a result, you usually only need to change a few properties for each
object.
Chapter 2 How to design a Windows Forms app 43

A form after the properties have been set

Control that’s Property that’s


selected being set

Description
•• The Properties window displays the properties for the object that’s currently
selected in the Form Designer window. To display the properties for another object,
click on that object or select the object from the drop-down list at the top of the
Properties window.
•• To change a property, enter a value into the text box or select a value from its drop-
down list if it has one. If a button with an ellipsis (…) appears at the right side of a
property’s text box, you can click on the ellipsis to display a dialog that lets you set
options for the property.
•• To change the properties for two or more controls at the same time, select the
controls. Then, the common properties of the controls are displayed in the
Properties window.
•• When you click on a property in the Properties window, a brief explanation of the
property appears in a pane at the bottom of the window. For more information,
press F1 to display the help information for the property.
•• You can use the first two buttons at the top of the Properties window to sort the
properties by category or alphabetically.
•• You can use the plus (+) and minus (-) signs displayed to the left of some of the
properties and categories in the Properties window to expand and collapse the list
of properties.

Note
•• If a description isn’t displayed when you click on a property in the Properties
window, right-click on the window and select Description from the shortcut menu.

Figure 2-5 How to set properties


44 Section 1 An introduction to Visual Studio

Common properties for forms and controls


Figure 2-6 shows some common properties for forms and controls. The
first two properties apply to both forms and controls. The other properties are
presented in two groups: properties that apply to forms and properties that apply
to controls. Note that some of the control properties only apply to certain types
of controls. That’s because different types of controls have different properties.
Since all forms and controls must have a Name property, Visual Studio
creates generic names for all forms and controls, such as Form1 or button1.
Often, though, you should change these generic names to something more
meaningful, especially if you’re going to refer to them in your C# code.
To make your program’s code easier to read and understand, you can begin
each name with a two- or three-letter prefix in lowercase letters to identify the
control’s type. Then, you can complete the name by describing the function of
the control. For instance, you can use a name like btnExit for the Exit button and
txtSubtotal for the Subtotal text box.
For Label controls, you can leave the generic names unchanged unless you
plan on modifying the properties of the labels in your code. For example, if you
want to use a label control to display a message to the user, you can give that
label a meaningful name such as lblMessage. But there’s no reason to change the
names for label controls that display text that won’t be changed by the program.
Forms and most controls also have a Text property that is visible when the
form is displayed. A form’s Text property is displayed in the form’s title bar. For
a control, the Text property is usually displayed somewhere within the control.
The Text property of a button, for example, is displayed on the button, and the
Text property of a text box is displayed in the text box.
As you work with properties, you’ll find that you can set some of them by
selecting a value from a drop-down list. For example, you can select a True or
False value for the TabStop property of a control. For other properties, you have
to enter a number or text value. And for some properties, a button with an ellipsis
(...) is displayed. Then, when you click this button, a dialog appears that lets you
set the property.
Chapter 2 How to design a Windows Forms app 45

The Name property


•• Sets the name you use to identify a form or control in your C# code.
•• Can be changed to provide a more descriptive and memorable name for forms and
controls that you will refer to when you write your code.
•• Doesn’t need to be changed for controls that you won’t refer to when you write
your code (such as most labels).
•• Can use a three-letter prefix to indicate whether the name refers to a form (frm),
button (btn), label (lbl), or text box (txt).

The Text property


•• Sets the text that’s displayed on a form or control. Some controls such as labels
display the generic name that’s generated by Visual Studio, which you’ll almost
always want to change.
•• For a form, the Text value is displayed in the title bar. For controls, the Text value is
displayed directly on the control.
•• For a text box, the Text value changes when the user types text into the control, and
you can write code that uses the Text property to get the text that was entered by
the user.

Other properties for forms


Property Description
AcceptButton Identifies the button that will be activated when the user presses the Enter key.
CancelButton Identifies the button that will be activated when the user presses the Esc key.
StartPosition Sets the position at which the form is displayed. To center the form, set this
property to CenterScreen.

Other properties for controls


Property Description
Enabled Determines whether the control will be enabled or disabled.
ReadOnly Determines whether the text in some controls like text boxes can be edited.
TabIndex Indicates the control’s position in the tab order, which determines the order in
which the controls will receive the focus when the user presses the Tab key.
TabStop Determines whether the control will accept the focus when the user presses
the Tab key to move from one control to another. Some controls, like labels,
don’t have the TabStop property because they can’t receive the focus.
TextAlign Sets the alignment for the text displayed on a control.

Figure 2-6 Common properties for forms and controls


46 Section 1 An introduction to Visual Studio

How to add navigation features


Windows forms have features that make it easier for users to move around
in the forms without using the mouse. These navigation features are described in
figure 2-7.
The tab order is the order in which the controls on a form receive the focus
when the user presses the Tab key. The tab order should usually be set so the
focus moves left-to-right and top-to-bottom, beginning at the top left of the form
and ending at the bottom right. However, in some cases you’ll want to deviate
from that order. For example, if you have controls arranged in columns, you may
want the tab order to move down each column.
The tab order is initially set based on the order in which you add controls
to the form. So, if you add the controls in the right order, you won’t need to
alter the tab order. But if you do need to change the tab order, you can do so
by adjusting the TabIndex property settings. The TabIndex property is simply
a number that represents the control’s position in the tab order, beginning
with zero. So, the first control in the tab order has a TabIndex of 0, the second
control’s TabIndex is 1, and so on.
Access keys are shortcut keys that let the user move the focus directly to a
control. You set a control’s access key by using the Text property. Just precede
the letter in the Text property value that you want to use as the access key with
an ampersand (&). Then, the user can move the focus to the control by pressing
Alt plus the access key.
If you assign an access key to a control that can’t receive the focus, such
as a label control, pressing the access key causes the focus to move to the next
control in the tab order that can receive the focus. As a result, you can use an
access key with a label control to create a shortcut for a text box control, which
can’t have an access key.
If you assign an access key to a button control, you should know that
pressing Alt plus the access key doesn’t simply move the focus to the control.
Instead, it activates the control just as if it was clicked. Without an access key,
a user would have to tab to the button control and then press the Enter key to
activate it using the keyboard. The exception is if the button is selected for the
AcceptButton or CancelButton property for the form.
The AcceptButton and CancelButton properties specify the buttons that are
activated when the user presses the Enter and Esc keys. That can make it easier
for a user to work with a form. If, for example, the AcceptButton property of the
Invoice Total form in figure 2-3 is set to the Calculate button, the user can press
the Enter key after entering a subtotal instead of using the mouse to click the
Calculate button or using the access key to activate it.
Chapter 2 How to design a Windows Forms app 47

How to adjust the tab order


•• Tab order refers to the sequence in which the controls receive the focus when the
user presses the Tab key. You should adjust the tab order so the Tab key moves the
focus from one control to the next in a logical sequence.
•• Each control has a TabIndex property that indicates the control’s position in the tab
order. You can change this property to change a control’s tab order position.
•• If you don’t want a control to receive the focus when the user presses the Tab key,
change that control’s TabStop property to False.
•• Label controls don’t have a TabStop property so they can’t receive the focus.

How to set access keys


•• Access keys are shortcut keys that the user can use in combination with the Alt key
to quickly move to individual controls on the form.
•• You use the Text property to set the access key for a control by placing an amper-
sand immediately before the letter you want to use for the access key. For example,
&Invoice sets the access key to I, but I&nvoice sets the access key to n.
•• Since the access keys aren’t case sensitive, &N and &n set the same access key.
•• When you set access keys, make sure to use a unique letter for each control. If
you don’t, the user may have to press the access key two or more times to select a
control.
•• You can’t set the access key for a text box. However, if you set an access key for
a label that immediately precedes the text box in the tab order, the access key will
take the user to the text box.
•• If you assign an access key to a button, the button is activated when you press Alt
plus the access key.

How to set the Enter and Esc keys


•• The AcceptButton property of the form sets the button that will be activated if the
user presses the Enter key.
•• The CancelButton property of the form sets the button that will be activated if the
user presses the Esc key. This property should usually be set to the Exit button.
•• You set the AcceptButton or CancelButton values by choosing the button from a
drop-down list that shows all the buttons on the form. So be sure to create and name
the buttons you want to use before you attempt to set these values.

Another way to set the tab order


•• In chapter 10, you’ll learn how to use Tab Order view to set the tab order of the
controls on the form. If the form consists of more than a few controls, that is the
best way to set that order.

Figure 2-7 How to add navigation features


48 Section 1 An introduction to Visual Studio

The property settings for the Invoice Total form


Figure 2-8 shows the property settings for the Invoice Total form. As you can
see, you don’t need to change many properties to finish the design of this form.
You only need to set four properties for the form, and you only use six of the
properties (Name, Text, TextAlign, ReadOnly, TabStop, and TabIndex) for the
controls. Depending on the order in which you create the controls, though, you
may not need to change the TabIndex settings.
Notice that the three text boxes that display the form’s calculations have
their ReadOnly property set to True. This setting gives the text boxes a shaded
appearance, as you saw in figure 2-3, and it prevents the user from entering text
into these controls. In addition, the TabStop property for these text boxes has
been set to False so the user can’t use the Tab key to move the focus to these
controls.
Finally, the settings for the TabIndex properties of the text box and the two
buttons are 1, 2, and 3. Since the label controls can’t receive the focus, and since
the TabStop property for the three read-only text boxes has been set to False, the
user can press the Tab key to move the focus from the Subtotal text box to the
Calculate button to the Exit button.
In addition, the Subtotal label has a TabIndex property of 0 and a Text
property that includes an access key of S. As a result, the user can press Alt+S to
move the focus to the control that has the next available tab index. In this case,
that control is the Subtotal text box, which has a TabIndex property of 1.
Of course, this is just one way that the TabIndex properties could be set. If,
for example, the TabIndex properties for the 10 controls were set from 0 through
9, from top to bottom in this summary, the tab order would work the same.
Chapter 2 How to design a Windows Forms app 49

The property settings for the form


Default name Property Setting
Form1 Text Invoice Total
AcceptButton btnCalculate
CancelButton btnExit
StartPosition CenterScreen

The property settings for the controls


Default name Property Setting
label1 Text &Subtotal:
TextAlign MiddleLeft
TabIndex 0
label2 Text Discount percent:
TextAlign MiddleLeft
label3 Text Discount amount:
TextAlign MiddleLeft
label4 Text Total:
TextAlign MiddleLeft
textBox1 Name txtSubtotal
TabIndex 1
textBox2 Name txtDiscountPercent
ReadOnly True
TabStop False
textBox3 Name txtDiscountAmount
ReadOnly True
TabStop False
textBox4 Name txtTotal
ReadOnly True
TabStop False
button1 Name btnCalculate
Text &Calculate
TabIndex 2
button2 Name btnExit
Text E&xit
TabIndex 3

Note
•• To provide an access key for the Subtotal text box, you can set the TabIndex and
Text properties for the Subtotal label as shown above.

Figure 2-8 The property settings for the Invoice Total form
50 Section 1 An introduction to Visual Studio

How to finish your design


When you’re working on a project, you may want to change the names of
some of the files from their defaults. Then, you’ll want to save the files with their
new names.

How to rename the files of a project


You may have noticed throughout this chapter that I didn’t change the
default name of the form (Form1.cs) that was added to the Invoice Total project
when the project was created. In practice, though, you usually change the name
of this form so it’s more descriptive. For example, figure 2-9 shows how to use
the Solution Explorer to change the name of the form file from Form1.cs to
frmInvoiceTotal.cs. When you do that, Visual Studio will also change the File
Name property for the form from Form1 to frmInvoiceTotal, and it will ask you
if you want to modify any references to the form.
You may also want to change the name of the project or solution. For
example, if you accepted the default project name when you started the
project (WindowsApp1.csproj), you may want to change it to something
more meaningful. Or, you may want to change the name of the solution so it’s
different from the project name. If so, you can use the technique presented in this
figure to do that too.

How to save the files of a project


Figure 2-9 also describes how to save the files of a project. Because Visual
Studio saves any changes you make to the files in a project when you build the
project, you won’t usually need to save them explicitly. However, it’s easy to do
if you need to.
When using the Save or Save All command, two factors determine which
files are saved: what’s selected in the Solution Explorer and the command you
use to perform the save operation. If, for example, a single file is selected, you
can use the Save command to save just that file, and you can use the Save All
command to save the file along with the project and solution that contain the file.
By contrast, if a project is selected in the Solution Explorer, the Save command
causes the entire project to be saved, and the Save All command causes the entire
solution to be saved.
If you haven’t saved all of your recent changes when you close a project,
Visual Studio will ask whether you want to save them. As a result, you don’t
need to worry that your changes will be lost.
Chapter 2 How to design a Windows Forms app 51

The Solution Explorer as a form file is being renamed

How to rename a file, project, or solution


•• You can rename a file, project, or solution by right-clicking on it in the Solution
Explorer window and selecting the Rename command from the shortcut menu. Or,
you can select the file, project, or solution in the Solution Explorer and press F2.
Then, you can enter the new name for the file, project, or solution.
•• Be sure not to change or omit the file extension when you rename a file. Remember
too that using a three-letter prefix to indicate the contents of the file (like frm for a
form file) makes it easier to tell what each file represents.
•• When you change the name of a form file, Visual Studio also changes the File
Name property for the file. It also asks you if you want to change all references to
the file, which is usually what you want.

How to save a file, project, or solution


•• You can use the Save All button in the Standard toolbar or the Save All command in
the File menu to save all files and projects in the solution.
•• You can use the Save button in the Standard toolbar or the Save command in the
File menu to save a file, project, or solution. The files that are saved depend on
what’s selected in the Solution Explorer window. If a single file is selected, just that
file is saved. If a project is selected, the entire project and its solution are saved.
And if a solution is selected, the entire solution and all its projects are saved.
•• If you try to close a solution that contains modified files, a dialog is displayed that
asks you if you want to save those files.

Figure 2-9 How to name and save the files of a project


52 Section 1 An introduction to Visual Studio

Perspective
If you can design the Invoice Total form that’s presented in this chapter,
you’ve taken a critical first step toward learning how to develop Windows
Forms apps with Visual Studio. The next step is to add the code that makes the
form work the way you want it to, and that’s what you’ll learn to do in the next
chapter.

Terms
template
label
text box
button
primary control
property
tab order
focus
access key

Exercise 2-1 Design the Invoice Total form


This exercise will guide you through the process of starting a new project and
developing the user interface for the Invoice Total form shown in this chapter.

Set the default path and start a new project


1. Start Visual Studio. If the Start window is displayed, click the “Continue
without code” link to display the IDE.
2. If you need to change the development settings so your menus are the same
as the ones in this book, use the procedure described in figure 2-1 to select the
default Visual C# settings.
3. If you want to stop the Start window from being displayed each time you start
Visual Studio, use the procedure described in figure 2-1 to change the startup
option to “Most recent solution” or “Empty environment”.
4. Start a new project as shown in figure 2-2. The project should be named
InvoiceTotal, it should be stored in the C:\C#\Ch02 folder, and the solution
should be stored in its own folder.
Add controls to the new form and set the properties
5. Use the techniques in figure 2-4 to add controls to the form so they have
approximately the same sizes and locations as in figure 2-5. But don’t worry
about the size of the labels, just their locations.
6. Select groups of controls and use the buttons in the Layout toolbar to size and
align the controls. But here again, let the labels automatically size themselves.
Then, size the form so it looks like the one in figure 2-4.
Chapter 2 How to design a Windows Forms app 53

7. Use the Properties window to set the properties for the form and its controls
so it looks like the form in figure 2-3. These properties are summarized in
figure 2-8.
Test the user interface
8. Press F5 to build and run the project. That should display the form in the
center of the screen, and it should look like the one in figure 2-3.
9. Experiment with the form to see what it can do. When you press the Tab key,
notice how the focus moves from one control to another. When you click
a button, notice how it indents and then pops back out just like any other
Windows button control. Nothing else happens in response to these button
clicks, though, because you haven’t written the code for them yet.
Notice that the Calculate button has a dark outline around it to indicate that its
function will be executed if you press the Enter key. (If it doesn’t have a dark
outline, you haven’t set the AcceptButton property of the form to the button.)
When you press the Alt key, notice that an underline appears under the s in
Subtotal, the first c in Calculate, and the x in Exit to indicate that you can use
an access key to work with these controls. (If the underlines don’t show, you
haven’t entered the Text properties correctly.)
10. If you notice that some of the properties are set incorrectly, click the Close
button in the upper right corner of the form to close the form. Then, make the
necessary changes and run the project again. When you’re satisfied that the
form is working right, close the form to return to the Form Designer.
Experiment with the properties for the form and its controls
11. In the Form Designer, click on the form so it is selected. Then, if necessary,
adjust the Properties window so you can see the description for each property.
To do that, drag the bottom boundary of the window up.
12. Click on the Categorized button at the top of the Properties window to display
the properties by category. Then, review the properties in the Appearance,
Behavior, Layout, and Window Style categories. Although you won’t under-
stand all of the descriptions, you should understand some of them.
13. In the Window Style category, change the settings for the MaximizeBox and
MinimizeBox to false to see how that changes the form. Then, to undo those
changes, click twice on the Undo button in the Standard toolbar or press
Ctrl+Z twice.
14. Click on the first text box and review the Appearance, Behavior, and Layout
properties for that control. Then, repeat this process for one of the labels and
one of the buttons. Here again, you won’t understand all of the descriptions,
but you should understand some of them.
15. Select all four of the labels, click on the plus sign before the Font property in
the Appearance group, and change the Bold setting to True to see how that
changes the form. Then, undo that change.
54 Section 1 An introduction to Visual Studio

Change the name of the form files


16. Use one of the techniques presented in figure 2-9 to change the name of the
form file from Form1.cs to frmInvoiceTotal.cs. When you do that, a dialog is
displayed that asks whether you want to change all the references to the form
name too. Click on Yes to close that dialog, and Visual Studio changes all
references to Form1 in the C# code to frmInvoiceTotal.
17. Note in the Solution Explorer that this also changes the name of the two
subordinate files to frmInvoiceTotal.Designer.cs and frmInvoiceTotal.resx.
Close the project and exit from Visual Studio
18. Use the FileClose Solution command to close the project. If you’ve
made any changes to the project since the last time you tested it, a dialog is
displayed that asks whether you want to save the changes that you made. If
you want to save those changes, click Yes.
19. Use the FileExit command to exit from Visual Studio.
How to build your C# programming skills
The easiest way is to let Murach’s C# (8th Edition) be your
guide! So if you’ve enjoyed this chapter, I hope you’ll get your
own copy of the book today. You can use it to:
• Teach yourself how to code C# using Windows Forms
applications

• Take advantage of all the time- and work-saving features


of Visual Studio as you develop C# applications
Mike Murach, Publisher
• Build database applications using Entity Framework (EF)
Core, ADO.NET, LINQ, and the DataGridView control
• Use object-oriented programming techniques the way the pros do
• Pick up a new skill whenever you want or need to by focusing on material that’s
new to you
• Look up coding details or refresh your memory on forgotten details when you’re in
the middle of developing a C# application
• Loan to your colleagues who will be asking you more and more questions about
C# programming
To get your copy, you can order online at www.murach.com or call us at
1-800-221-5528 (toll-free in the U.S. and Canada). And remember, when you order
directly from us, this book comes with my personal guarantee:

100% Guarantee
When you buy directly from us, you must be
satisfied. Try our books for 30 days or our eBooks
for 14 days. They must outperform any competing
book or course you’ve ever tried, or return your
purchase for a prompt refund.…no questions asked.

Thanks for your interest in Murach books!

You might also like