VB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 208

Contents

Visual Basic Tutorials


Overview
About Visual Studio
About the code editor
About projects and solutions
More Visual Studio features
Create an app
Create a console app
Create a UWP app
Create a WPF app
Create a web app
Create your first Windows Forms app
Create a simple Windows Forms app
Tutorial 1: Create a picture viewer (VB)
1. Create Picture Viewer app
2. Add controls to the app
3. Code, test, and run the app
Tutorial 2: Create a timed math quiz (VB)
1. Create the math quiz app
2. Add math problems to the app
3. Add a timer to the app
4. Customize the app
Tutorial 3: Create a matching game (VB)
1. Create a matching game
2. Add icons to your match game
3. Add labels and a timer
4. Play your match game
Learn Visual Studio
Open a project from a repo
Write and edit code
Compile and build
Debug your code
Unit testing
Deploy your project
Access data
Welcome to the Visual Studio IDE | Visual Basic
6/24/2022 • 14 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
An integrated development environment (IDE) is a feature-rich program that supports many aspects of software
development. The Visual Studio IDE is a creative launching pad that you can use to edit, debug, and build code,
and then publish an app. Over and above the standard editor and debugger that most IDEs provide, Visual
Studio includes compilers, code completion tools, graphical designers, and many more features to enhance the
software development process.

The preceding image shows Visual Studio with an open Visual Basic project that shows key windows and their
functionality:
In Solution Explorer, at upper right, you can view, navigate, and manage your code files. Solution
Explorer can help organize your code by grouping the files into solutions and projects.
The central editor window, where you'll probably spend most of your time, displays file contents. In the
editor window, you can edit code or design a user interface such as a window with buttons and text
boxes.
In Team Explorer, at lower right, you can track work items and share code using version control technologies
such as Git and Team Foundation Version Control (TFVC).
In Git Changes at lower right, you can track work items and share code with others by using version control
technologies like Git and GitHub.

Editions
Visual Studio is available for Windows and Mac. Visual Studio for Mac has many of the same features as Visual
Studio for Windows, and is optimized for developing cross-platform and mobile apps. This article focuses on the
Windows version of Visual Studio.
There are three editions of Visual Studio: Community, Professional, and Enterprise. See Compare Visual Studio
editions to learn about which features each edition supports.

Popular productivity features


Some popular features in Visual Studio that improve your productivity when developing software include:
Squiggles and Quick Actions
Squiggles are wavy underlines that alert you to errors or potential problems in your code as you type.
These visual clues help you fix problems immediately, without waiting to discover errors during build or
runtime. If you hover over a squiggle, you see more information about the error. A lightbulb might also
appear in the left margin showing Quick Actions you can take to fix the error.

Refactoring
Refactoring includes operations such as intelligent renaming of variables, extracting one or more lines of
code into a new method, and changing the order of method parameters.
IntelliSense
IntelliSense is a set of features that display information about your code directly in the editor and, in
some cases, write small bits of code for you. It's like having basic documentation inline in the editor, so
you don't have to look up type information elsewhere.
The following illustration shows how IntelliSense displays a member list for a type:

IntelliSense features vary by language. For more information, see C# IntelliSense, Visual C++ IntelliSense,
JavaScript IntelliSense, and Visual Basic IntelliSense.
Visual Studio search
Visual Studio menus, options, and properties can seem overwhelming at times. Visual Studio search, or
Ctrl +Q , is a great way to rapidly find IDE features and code in one place.
When you start typing the name of something you're looking for, Visual Studio lists results that take you
where you need to go. If you need to add functionality, for example another programming language, you
can open the Visual Studio Installer from the search box results to install the workload or component.

Live Share
Collaboratively edit and debug with others in real time, regardless of your app type or programming
language. You can instantly and securely share your project. You can also share debugging sessions,
terminal instances, localhost web apps, voice calls, and more.
Call Hierarchy
The Call Hierarchy window shows the methods that call a selected method. This information can be
useful when you're thinking about changing or removing the method, or when you're trying to track
down a bug.
CodeLens
CodeLens helps you find code references, code changes, linked bugs, work items, code reviews, and unit
tests, without leaving the editor.

Go To Definition
The Go To Definition feature takes you directly to the location of a function or type definition.
Peek Definition
The Peek Definition window shows a method or type definition without opening a separate file.

Install Visual Studio


In this section, you create a simple project to try out some of the things you can do with Visual Studio. You learn
how to change the color theme, use IntelliSense as a coding aid, and debug an app to see a variable value during
app execution.
To get started, download Visual Studio and install it on your system. The modular installer enables you to select
and install workloads, which are groups of features needed for the programming language or platform you
prefer. To follow the steps for creating a program, be sure to select the .NET Core cross-platform
development workload during installation.

To get started, download Visual Studio and install it on your system. In the modular installer, you choose and
install workloads, which are groups of features you need for the programming languages or platforms you
want. To use the following steps to create a program, be sure to select the .NET desktop development
workload during installation.

When you open Visual Studio for the first time, you can sign in by using your Microsoft account or your work or
school account.

Customize Visual Studio


You can personalize the Visual Studio user interface, including changing the default color theme.
Change the color theme
To change the color theme:
1. Open Visual Studio. On the start window, select Continue without code .

The IDE opens.


2. On the Visual Studio menu bar, choose Tools > Options to open the Options dialog.
3. On the Environment > General options page, change the Color theme selection to Dark , and then
choose OK .

The color theme for the entire IDE changes to Dark .

1. Open Visual Studio. On the start window, select Continue without code .
2. On the Visual Studio menu bar, choose Tools > Options to open the Options dialog.
3. On the Environment > General options page, change the Color Theme selection to Blue or Light ,
and then select OK .

The color theme for the entire IDE changes accordingly. The following screenshot shows the Blue theme:
Select environment settings
You can configure Visual Studio to use environment settings tailored to Visual Basic developers.
1. On the menu bar, choose Tools > Impor t and Expor t Settings .
2. In the Impor t and Expor t Settings Wizard , select Reset all settings , and then select Next .
3. On the Save Current Settings page, select whether to save your current settings before resetting. If you
haven't customized any settings, select No, just reset settings, over writing my current settings .
Then select Next .
4. On the Choose a Default Collection of Settings page, choose Visual Basic , and then select Finish .
5. On the Reset Complete page, select Close .
To learn about other ways you can personalize the IDE, see Personalize Visual Studio.

Create a program
Dive in and create a simple program.
1. On the Visual Studio menu bar, choose File > New > Project . (Alternatively, press Ctrl +Shift +N .)

The Create a new project window opens and shows several project templates. A template contains the
basic files and settings required for a given project type.
2. To find the template we want, type or enter .net core console in the search box. The list of available
templates is automatically filtered based on the keywords you entered. You can further filter the template
results by choosing Visual Basic from the All language drop-down list, Windows from the All
platforms list, and Console from the All project types list.
Select the Console Application template, and then click Next .

3. In the Configure your new project window, enter HelloWorld in the Project name box, optionally
change the directory location for your project files (the default locale is C:\Users\<name>\source\repos ),
and then click Next .

4. In the Additional information window, verify that .NET Core 3.1 appears in the Target Framework
drop-down menu, and then click Create .
Visual Studio creates the project. It's a simple "Hello World" application that calls the Console.WriteLine()
method to display the literal string "Hello World!" in the console (program output) window.
Shortly, you should see something like the following:

The Visual Basic code for the app appears in the editor window, which takes up most of the space. Notice
that the text is automatically colorized to indicate different parts of the code, such as keywords and types.
In addition, small, vertical dashed lines in the code indicate which braces match one another, and line
numbers help you locate code later. You can choose the small, boxed minus signs to collapse or expand
blocks of code. This code outlining feature lets you hide code you don't need, helping to minimize
onscreen clutter. The project files are listed on the right side in a window called Solution Explorer .
There are other menus and tool windows available, but let's move on for now.
5. Now, start the app. You can do this by choosing Star t Without Debugging from the Debug menu on
the menu bar. You can also press Ctrl +F5 .

Visual Studio builds the app, and a console window opens with the message Hello World! . You now
have a running app!
6. To close the console window, press any key on your keyboard.
7. Let's add some additional code to the app. Add the following Visual Basic code before the line that says
Console.WriteLine("Hello World!") :

Console.WriteLine("What is your name?")


Dim name = Console.ReadLine()

This code displays What is your name? in the console window, and then waits until the user enters
some text followed by the Enter key.
8. Change the line that says Console.WriteLine("Hello World!") to the following code:

Console.WriteLine("Hello " + name + "!")

9. Run the app again by pressing Ctrl +F5 .


Visual Studio rebuilds the app, and a console window opens and prompts you for your name.
10. Enter your name in the console window and press Enter .

11. Press any key to close the console window and stop the running program.
1. On the Visual Studio menu bar, choose File > New > Project . You can also press Ctrl +Shift +N .

The Create a new project window opens and shows several project templates. A template contains the
basic files and settings that a given project type requires.
2. To find a template, you can type or enter keywords in the search box. The list of available templates filters
based on the keywords you enter. You can further filter the template results by choosing Visual Basic
from the All languages dropdown list, Windows from the All platforms list, and Console from the
All project types list.
Select the Visual Basic Console Application template, and then select Next .

3. In the Configure your new project window, enter HelloWorld in the Project name box. Optionally,
change the project directory location from the default location of C:\Users\<name>\source\repos, and
then select Next .

4. In the Additional information window, verify that .NET 6.0 appears in the Target Framework drop-
down menu, and then select Create .

Visual Studio creates the project. The program is a simple "Hello World" application that calls the
Console.WriteLine() method to display the string Hello, World! in a console window.
The project files appear on the right side of the Visual Studio IDE, in a window called the Solution
Explorer . In the Solution Explorer window, select the Program.vb file. The Visual Basic code for the
app opens in the central editor window, which takes up most of the space.

The code is automatically colorized to indicate different parts, such as keywords and types. Line numbers
help you locate code.
Small, vertical dashed lines in the code indicate code structure or code blocks that go together. You can
also select the small, boxed minus or plus signs to collapse or expand blocks of code. This code outlining
feature lets you hide code you don't need to see, helping to minimize onscreen clutter.
Many other menus and tool windows are available.
5. Start the app by choosing Debug > Star t Without Debugging from the Visual Studio top menu. You
can also press Ctrl +F5 .

Visual Studio builds the app, and a console window opens with the message Hello World! . You now
have a running app!

6. To close the console window, press any key.


7. Let's add more code to the app. Add the following Visual Basic code before the line that says
Console.WriteLine("Hello World!") :
Console.WriteLine("What is your name?")
Dim name = Console.ReadLine()

This code displays What is your name? in the console window, and then waits until the user enters
some text.
8. Change the line that says Console.WriteLine("Hello World!") to the following line:

Console.WriteLine("Hello " + name + "!")

9. Run the app again by selecting Debug > Star t Without Debugging or pressing Ctrl +F5 .
Visual Studio rebuilds the app, and a console window opens and prompts you for your name.
10. Type your name in the console window and press Enter .

11. Press any key to close the console window and stop the running program.

Use refactoring and IntelliSense


Let's look at a couple of the ways that refactoring and IntelliSense can help you code more efficiently.
First, rename the name variable:
1. Double-click the name variable, and type the new name for the variable, username.
A box appears around the variable, and a light bulb appears in the margin.
2. Select the lightbulb icon to show the available Quick Actions. Select Rename 'name' to 'username' .
The variable renames across the project, which in this case is only two places.
Now take a look at IntelliSense.
1. Below the line that says Console.WriteLine("Hello " + username + "!") , type the following code:

Dim now = Date.

A box displays the members of the DateTime class. The description of the currently selected member also
displays in a separate box.

2. Choose the member named Now , which is a property of the class. Either double-click on Now , or select
it and press Tab .
3. Below that line, enter the following lines of code:

Dim dayOfYear = now.DayOfYear


Console.Write("Day of year: ")
Console.WriteLine(dayOfYear)
TIP
Console.Write is different from Console.WriteLine in that it doesn't add a line terminator after it prints. That means
that the next piece of text that's sent to the output will print on the same line. You can hover over each of these
methods in your code to see their descriptions.

Next, use refactoring again to make the code a little more concise.
1. Select the variable now in the line Dim now = Date.Now . A screwdriver icon appears in the margin on that
line.
2. Select the screwdriver icon to see available suggestions from Visual Studio. This case shows the Inline
temporary variable refactoring to remove a line of code without changing the overall code behavior.

3. Select Inline temporar y variable to refactor the code.


4. Run the program again by pressing Ctrl +F5 . The output looks something like this:

1. Select the variable now in the line Dim now = Date.Now . A lightbulb icon appears in the margin on that
line.
2. Select the lightbulb icon to see available suggestions from Visual Studio. This case shows the Inline
temporary variable refactoring to remove a line of code without changing the overall code behavior.

3. Select Inline temporar y variable to refactor the code.


4. Run the program again by pressing Ctrl +F5 . The output looks something like this:
Debug code
When you write code, you should run it and test it for bugs. Visual Studio's debugging system lets you step
through code one statement at a time and inspect variables as you go. You can set breakpoints that stop
execution of the code at a particular line, and observe how the variable value changes as the code runs.
Set a breakpoint to see the value of the username variable while the program is running.
1. Set a breakpoint on the line of code that says Console.WriteLine("Hello " + username + "!") by clicking in
the far-left margin, or gutter, next to the line. You can also select the line of code and then press F9 .
A red circle appears in the gutter, and the line is highlighted.
2. Start debugging by selecting Debug > Star t Debugging or pressing F5 .
3. When the console window appears and asks for your name, enter your name.
The focus returns to the Visual Studio code editor, and the line of code with the breakpoint is highlighted
in yellow. The yellow highlight means that this line of code will execute next. The breakpoint makes the
app pause execution at this line.
4. Hover your mouse over the username variable to see its value. You can also right-click on username and
select Add Watch to add the variable to the Watch window, where you can also see its value.

5. Press F5 again to finish running the app.


For more information about debugging in Visual Studio, see the Debugger feature tour.

Next steps
Explore Visual Studio further by following along with one of these introductory articles:
Learn to use the code editor
Learn about projects and solutions

See also
Discover more Visual Studio features.
Visit visualstudio.microsoft.com.
Read the Visual Studio blog.
Learn to use the code editor with Visual Basic
6/24/2022 • 10 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this 10-minute introduction to the code editor in Visual Studio, we'll add code to a file to look at some of the
ways that Visual Studio makes writing, navigating, and understanding Visual Basic code easier.

TIP
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

This article assumes you're already familiar with Visual Basic. If you aren't, we suggest you look at a tutorial such
as Create a simple Visual Basic (VB) console app first.

TIP
To follow along with this article, make sure you have the Visual Basic settings selected for Visual Studio. For information
about selecting settings for the integrated development environment (IDE), see Select environment settings.

Create a new code file


Start by creating a new file and adding some code to it.
1. Open Visual Studio. Press Esc or click Continue without code on the start window to open the
development environment.
2. From the File menu on the menu bar, choose New File .
3. In the New File dialog box, under the General category, choose Visual Basic Class , and then choose
Open .
A new file opens in the editor with the skeleton of a Visual Basic class. (You can already notice that you
don't have to create a full Visual Studio project to gain some of the benefits that the code editor offers,
such as syntax highlighting. All you need is a code file!)
1. Open Visual Studio. Press Esc or select Continue without code on the start window to open the
development environment.
2. From the File menu on the menu bar, choose New > File .
3. In the New File dialog box, under the General category, choose Visual Basic Class , and then choose
Open .
A new file opens in the editor with the skeleton of a Visual Basic class. (You can already notice that you
don't have to create a full Visual Studio project to gain some of the benefits that the code editor offers,
such as syntax highlighting. All you need is a code file!)

Use code snippets


Visual Studio provides useful code snippets that you can use to quickly and easily generate commonly used
code blocks. Code snippets are available for different programming languages including Visual Basic, C#, and
C++. Let's add the Visual Basic Sub snippet to our file.
1. Place your cursor above the line that says End Class , and type sub .
A pop-up dialog box appears with information about the Sub keyword and how to insert the Sub code
snippet.

2. Press Tab twice to insert the code snippet.


The outline for the Sub procedure MySub() is added to the file.
The available code snippets vary for different programming languages. You can look at the available code
snippets for Visual Basic by choosing Edit > IntelliSense > Inser t Snippet (or press Ctrl +K , Ctrl +X ). For
Visual Basic, code snippets are available for the following categories:
There are snippets for determining if a file exists on the computer, writing to a text file, reading a registry value,
executing a SQL query, or creating a For Each...Next statement, and many more.
1. Place your cursor above the line that says End Class , and type sub .
A pop-up dialog box appears with information about the Sub keyword and how to insert the Sub code
snippet.

2. Press Tab twice to insert the code snippet.


The outline for the Sub procedure MySub() is added to the file.
The available code snippets vary for different programming languages. You can look at the available code
snippets for Visual Basic by opening the right-click or context menu in the code editor and choosing Snippet >
Inser t Snippet (or press Ctrl +K , Ctrl +X ). For Visual Basic, code snippets are available for the following
categories:

Comment out code


The toolbar, which is the row of buttons under the menu bar in Visual Studio, can help make you more
productive as you code. For example, you can toggle IntelliSense completion mode, increase or decrease a line
indent, or comment out code that you don't want to compile. (IntelliSense is a coding aid that displays a list of
matching methods, amongst other things.) In this section, we'll comment out some code.

1. Paste the following code into the MySub() procedure body.


' _words is a string array that we'll sort alphabetically
Dim _words = New String() {
"the",
"quick",
"brown",
"fox",
"jumps"
}

Dim morewords = New String() {


"over",
"the",
"lazy",
"dog"
}

Dim query = From word In _words


Order By word.Length
Select word

2. We're not using the morewords array, but we may use it later so we don't want to completely delete it.
Instead, let's comment out those lines. Select the entire definition of morewords to the closing curly brace,
and then choose the Comment out the selected lines button on the toolbar. If you prefer to use the
keyboard, press Ctrl +K , Ctrl +C .

The Visual Basic comment character ' is added to the beginning of each selected line to comment out
the code.

1. Paste the following code into the MySub() procedure body.

' _words is a string array that we'll sort alphabetically


Dim _words = New String() {
"the",
"quick",
"brown",
"fox",
"jumps"
}

Dim morewords = New String() {


"over",
"the",
"lazy",
"dog"
}

Dim query = From word In _words


Order By word.Length
Select word

2. We're not using the morewords array, but we may use it later so we don't want to completely delete it.
Instead, let's comment out those lines. Select the entire definition of morewords to the closing curly brace,
and then choose the Comment out the selected lines button on the toolbar. If you prefer to use the
keyboard, press Ctrl +K , Ctrl +C .
The Visual Basic comment character ' is added to the beginning of each selected line to comment out
the code.

Collapse code blocks


You can collapse sections of code to focus just on the parts that are of interest to you. To practice, let's collapse
the _words array to one line of code. Choose the small gray box with the minus sign inside it in the margin of
the line that says Dim _words = New String() { . Or, if you're a keyboard user, place the cursor anywhere in the
array definition and press Ctrl +M , Ctrl +M .

The code block collapses to just the first line, followed by an ellipsis ( ... ). To expand the code block again, click
the same gray box that now has a plus sign in it, or press Ctrl +M , Ctrl +M again. This feature is called Outlining
and is especially useful when you're collapsing long methods or entire classes.
You can collapse sections of code to focus just on the parts that are of interest to you. To practice, let's collapse
the _words array to one line of code. Choose the small gray box with the minus sign inside it in the margin of
the line that says Dim _words = New String() { . Or, if you're a keyboard user, place the cursor anywhere in the
array definition and press Ctrl +M , Ctrl +M .

The code block collapses to just the first line, followed by an ellipsis ( ... ). To expand the code block again,
choose the same gray box that now has a plus sign in it, or press Ctrl +M , Ctrl +M again. This feature is called
Outlining and is especially useful when you're collapsing long methods or entire classes.

View symbol definitions


The Visual Studio editor makes it easy to inspect the definition of a type, method, etc. One way is to navigate to
the file that contains the definition, for example by choosing Go to Definition anywhere the symbol is
referenced. An even quicker way that doesn't move your focus away from the file you're working in is to use
Peek Definition. Let's peek at the definition of the String type.
1. Right-click on the word String and choose Peek Definition from the content menu. Or, press Alt +F12 .
A pop-up window appears with the definition of the String class. You can scroll within the pop-up
window, or even peek at the definition of another type from the peeked code.
2. Close the peeked definition window by choosing the small box with an "x" at the top right of the pop-up
window.
The Visual Studio editor makes it easy to inspect the definition of a type or class member. One way is to navigate
to the file that contains the definition, for example by choosing Go to Definition anywhere the symbol is
referenced. An even quicker way that doesn't move your focus away from the file you're working in is to use
Peek Definition. Let's peek at the definition of the String type.
1. Right-click on the word String and choose Peek Definition from the content menu. Or, press Alt +F12 .
A pop-up window appears with the definition of the String class. You can scroll within the pop-up
window, or even peek at the definition of another type from the peeked code.

2. Close the peek definition window by choosing the small box with an "x" at the top right of the pop-up
window.

Use IntelliSense to complete words


IntelliSense is an invaluable resource when you're coding. It can show you information about available members
of a type, or parameter details for different overloads of a method. You can also use IntelliSense to complete a
word after you type enough characters to disambiguate it. Let's add a line of code to print out the ordered
strings to the console window, which is the standard place for output from the program to go.
1. Below the query variable, start typing the following code:

For Each str In qu

You see IntelliSense show you Quick Info about the query symbol.

2. To insert the rest of the word query by using IntelliSense's word completion functionality, press Tab .
3. Finish off the code block to look like the following code.
For Each str In query
Console.WriteLine(str)
Next

IntelliSense is an invaluable resource when you're coding. It can show you information about available members
of a type, or parameter details for different overloads of a method. You can also use IntelliSense to complete a
word after you type enough characters to disambiguate it. Let's add a line of code to print out the ordered
strings to the console window, which is the standard place for output from the program to go.
1. Below the query variable, start typing the following code:

For Each str In qu

You see IntelliSense show you Quick Info about the query symbol.

2. To insert the rest of the word query by using IntelliSense's word completion functionality, press Tab .
3. Finish off the code block to look like the following code.

For Each str In query


Console.WriteLine(str)
Next

Refactor a name
Nobody gets code right the first time, and one of the things you might have to change is the name of a variable
or method. Let's try out Visual Studio's refactor functionality to rename the _words variable to words .
1. Place your cursor over the definition of the _words variable and choose Rename from the right-click or
context menu.
A pop-up Rename dialog box appears at the top right of the editor.
2. With the variable _words still selected, type in the desired name of words . Notice that the reference to
words in the query is also automatically renamed. Before you press Enter or click Apply , select the
Include comments checkbox in the Rename pop-up box.

3. Press Enter or click Apply .


Both occurrences of words are renamed, as well as the reference to words in the code comment.

Nobody gets code right the first time, and one of the things you might have to change is the name of a variable
or method. Let's try out Visual Studio's refactor functionality to rename the _words variable to words .
1. Place your cursor over the definition of the _words variable and choose Rename from the right-click or
context menu.
A pop-up Rename dialog box appears at the top right of the editor.
2. With the variable _words still selected, type in the desired name of words . Notice that the reference to
words in the query is also automatically renamed. Before you press Enter or Apply , select the Include
comments checkbox in the Rename pop-up box.

3. Press Enter or choose Apply .


Both occurrences of words are renamed, as well as the reference to words in the code comment.

Next steps
Learn about projects and solutions

See also
Code snippets
Navigate code
Outlining
Go To Definition and Peek Definition
Refactoring
Use IntelliSense
Learn about projects and solutions using Visual
Basic
6/24/2022 • 10 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this introductory article, we'll explore what it means to create a solution and a project in Visual Studio. A
solution is a container that's used to organize one or more related code projects, for example a class library
project and a corresponding test project. We'll look at the properties of a project and some of the files it can
contain. We'll also create a reference from one project to another.

TIP
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

We'll construct a solution and project from scratch as an educational exercise to understand the concept of a
project. In your general use of Visual Studio, you'll likely use some of the various project templates that Visual
Studio offers when you create a new project.

NOTE
Solutions and projects aren't required to develop apps in Visual Studio. You can also just open a folder that contains code
and start coding, building, and debugging. For example, if you clone a GitHub repo, it might not contain Visual Studio
projects and solutions. For more information, see Develop code in Visual Studio without projects or solutions.

Solutions and projects


Despite its name, a solution is not an "answer". A solution is simply a container used by Visual Studio to
organize one or more related projects. When you open a solution in Visual Studio, it automatically loads all the
projects that the solution contains.
Create a solution
We'll start our exploration by creating an empty solution. After you get to know Visual Studio, you probably
won't find yourself creating empty solutions often. When you create a new project, Visual Studio automatically
creates a solution to house the project if there's not a solution already open.
1. Open Visual Studio.
2. On the start window, choose Create a new project .
3. On the Create a new project page, enter blank solution into the search box, select the Blank
Solution template, and then choose Next .
4. Name the solution QuickSolution , and then choose Create .
A solution appears in Solution Explorer on the right-hand side of the Visual Studio window. You'll
probably use Solution Explorer often, to browse the contents of your projects.
1. Open Visual Studio.
2. On the start window, choose Create a new project .
3. On the Create a new project page, enter blank solution into the search box, select the Blank
Solution template, and then choose Next .

4. Name the solution QuickSolution , and then choose Create .


A solution appears in Solution Explorer on the right-hand side of the Visual Studio window. You'll
probably use Solution Explorer often, to browse the contents of your projects.
Add a project
Now let's add our first project to the solution. We'll start with an empty project and add the items we need to the
project.
1. From the right-click or context menu of Solution 'QuickSolution' in Solution Explorer , choose Add >
New Project .
A dialog box opens that says Add a new project .
2. Enter the text empty into the search box at the top, and then select Visual Basic under Language .
3. Select the Empty Project (.NET Framework) template, and then choose Next .
4. Name the project QuickDate , then choose Create .
A project named QuickDate appears beneath the solution in Solution Explorer . Currently it contains a
single file called App.config.

NOTE
If you don't see the Empty Project (.NET Framework) template, you need to install the .NET desktop
development Visual Studio workload. Visual Studio uses workload-based installation to only install the
components you need for the type of development you do. An easy way to install a new workload when you're
creating a new project is to choose the Install more tools and features link under the text that says Not
finding what you're looking for? . After Visual Studio Installer launches, choose the .NET desktop
development workload and then the Modify button.

1. From the right-click or context menu of Solution 'QuickSolution' in Solution Explorer , choose Add >
New Project .
A dialog box opens that says Add a new project .
2. Enter the text empty into the search box at the top, and then select Visual Basic in the All languages
drop-down list.
3. Select the Empty Project (.NET Framework) template, and then choose Next .
4. Name the project QuickDate , then choose Create .
A project named QuickDate appears beneath the solution in Solution Explorer . Currently it contains a
single file called App.config.

NOTE
If you don't see the Empty Project (.NET Framework) template, you need to install the .NET desktop
development Visual Studio workload. Visual Studio uses workload-based installation to only install the
components you need for the type of development you do. An easy way to install a new workload when you're
creating a new project is to choose the Install more tools and features link under the text that says Not
finding what you're looking for? . After Visual Studio Installer launches, choose the .NET desktop
development workload and then the Modify button.

Add an item to the project


We have an empty project. Let's add a code file.
1. From the right-click or context menu of the QuickDate project in Solution Explorer , choose Add >
New Item .
The Add New Item dialog box opens.
2. Expand Common Items , then choose Code . In the middle pane, choose the Class item template. Name
the class Calendar , and then choose the Add button.
A file named Calendar.vb is added to the project. The .vb on the end is the file extension that's given to
Visual Basic code files. The file appears in the visual project hierarchy in Solution Explorer , and its
contents open in the editor.
3. Replace the contents of the Calendar.vb file with the following code:
Class Calendar
Public Shared Function GetCurrentDate() As Date
Return DateTime.Now.Date
End Function
End Class

The Calendar class contains a single function, GetCurrentDate , that returns the current date.
4. Open the project properties by double-clicking My Project in Solution Explorer . On the Application
tab, change Application type to Class Librar y . This step is necessary to build the project successfully.
5. Build the project by right-clicking on QuickDate in Solution Explorer and choosing Build . You should
see a successful build message in the Output window.

Add a second project


It's common for solutions to contain more than one project, and often these projects reference each other. Some
projects in a solution might be class libraries, some executable applications, and some might be unit test
projects or websites.
Let's add a unit test project to our solution. This time we'll start from a project template so we don't have to add
an additional code file to the project.
1. From the right-click or context menu of Solution 'QuickSolution' in Solution Explorer , choose Add >
New Project .
2. In the Add a new project dialog box, enter the text unit test into the search box at the top, and then
select Visual Basic under Language .
3. Choose the Unit Test Project (.NET Framework) project template, and then choose Next .
4. Name the project QuickTest , and then choose Create .
A second project is added to Solution Explorer , and a file named UnitTest1.vb opens in the editor.
2. In the Add a new project dialog box, enter the text unit test into the search box at the top, and then
select Visual Basic in the All languages drop-down list.
3. Choose the Unit Test Project (.NET Framework) project template, and then choose Next .
4. Name the project QuickTest , and then choose Create .
A second project is added to Solution Explorer , and a file named UnitTest1.vb opens in the editor.

Add a project reference


We're going to use the new unit test project to test our method in the QuickDate project, so we need to add a
reference to that project. The reference creates a build dependency between the two projects, meaning that
when you build the solution, QuickDate is built before QuickTest .
1. Choose the References node in the QuickTest project, and from the right-click or context menu, choose
Add Reference .
The Reference Manager dialog box opens.
2. In the left pane, expand Projects and choose Solution . In the middle pane, choose the checkbox next to
QuickDate , and then choose the OK button.
A reference to the QuickDate project is added.
1. Choose the References node in the QuickTest project, and from the right-click or context menu, choose
Add Reference .

The Reference Manager dialog box opens.


2. In the left pane, expand Projects and choose Solution . In the middle pane, choose the checkbox next to
QuickDate , and then choose the OK button.
A reference to the QuickDate project is added.
Add test code
1. Now we'll add test code to the Visual Basic code file. Replace the contents of UnitTest1.vb with the
following code.

<TestClass()> Public Class UnitTest1

<TestMethod()> Public Sub TestGetCurrentDate()


Assert.AreEqual(Date.Now.Date, QuickDate.Calendar.GetCurrentDate())
End Sub

End Class

You'll see a red squiggle under some of the code. We'll fix this error by making the test project a friend
assembly to the QuickDate project.
2. Back in the QuickDate project, open the Calendar.vb file if it's not already open, and add the following
Imports statement and InternalsVisibleToAttribute attribute, to resolve the error in the test project.

Imports System.Runtime.CompilerServices

<Assembly: InternalsVisibleTo("QuickTest")>

The code file should look like this:

1. Now we'll add test code to the Visual Basic code file. Replace the contents of UnitTest1.vb with the
following code.

<TestClass()> Public Class UnitTest1

<TestMethod()> Public Sub TestGetCurrentDate()


Assert.AreEqual(Date.Now.Date, QuickDate.Calendar.GetCurrentDate())
End Sub

End Class

You'll see a red squiggle under some of the code. We'll fix this error by making the test project a friend
assembly to the QuickDate project.
2. Back in the QuickDate project, open the Calendar.vb file if it's not already open, and add the following
Imports statement and InternalsVisibleToAttribute attribute, to resolve the error in the test project.
Imports System.Runtime.CompilerServices

<Assembly: InternalsVisibleTo("QuickTest")>

The code file should look like this:

Project properties
The line in the Calendar.vb file that contains the InternalsVisibleToAttribute attribute references the assembly
name (file name) of the QuickTest project. The assembly name might not always be the same as the project
name. To find the assembly name of a project, open the project properties.
1. In Solution Explorer , select the QuickTest project. From the right-click or context menu, select
Proper ties , or just press Alt +Enter . (You can also double-click My Project in Solution Explorer .)
The property pages for the project open on the Application tab. The property pages contain various
settings for the project. Notice that the assembly name of the QuickTest project is indeed "QuickTest". If
you wanted to change the assembly name, this is where you'd do that. Then, when you build the test
project, the name of the resulting binary file would change from QuickTest.dll to whatever you chose.

2. Explore some of the other tabs of the project's property pages, such as Compile and Settings . These
tabs are different for different types of projects.
The line in the Calendar.vb file that contains the InternalsVisibleToAttribute attribute, references the assembly
name (file name) of the QuickTest project. The assembly name might not always be the same as the project
name. To find the assembly name of a project, open the project properties.
1. In Solution Explorer , select the QuickTest project. From the right-click or context menu, select
Proper ties , or just press Alt +Enter . (You can also double-click My Project in Solution Explorer .)
The property pages for the project open on the Application tab. The property pages contain various
settings for the project. Notice that the assembly name of the QuickTest project is indeed "QuickTest". If
you wanted to change the assembly name, this is where you'd do that. Then, when you build the test
project, the name of the resulting binary file would change from QuickTest.dll to whatever you chose.

2. Explore some of the other tabs of the project's property pages, such as Compile and Settings . These
tabs are different for different types of projects.

(Optional) Run the test


If you want to check that your unit test is working, choose Test > Run > All Tests from the menu bar. A window
called Test Explorer opens, and you should see that the TestGetCurrentDate test passes.

TIP
If Test Explorer doesn't open automatically, open it by choosing Test > Windows > Test Explorer from the menu bar.

If you want to check that your unit test is working, choose Test > Run All Tests from the menu bar. A window
called Test Explorer opens, and you should see that the TestGetCurrentDate test passes.
TIP
If Test Explorer doesn't open automatically, open it by choosing Test > Windows > Test Explorer from the menu bar.

Next steps
If you want to further explore Visual Studio, consider creating an app by following one of the Visual Basic
tutorials.

See also
Create projects and solutions
Manage project and solution properties
Manage references in a project
Develop code in Visual Studio without projects or solutions
Visual Studio IDE overview
Features of Visual Studio
6/24/2022 • 6 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This article describes features for experienced developers, or developers who are already familiar with Visual
Studio. For a basic introduction to Visual Studio, see the Visual Studio IDE overview.

Modular installation
In Visual Studio's modular installer, you choose and install the workloads you want. Workloads are groups of
features that programming languages or platforms need to work. This modular strategy helps keep the Visual
Studio installation footprint smaller, so it installs and updates faster.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
To learn more about setting up Visual Studio on your system, see Install Visual Studio.

Create cloud-enabled Azure apps


Visual Studio has a suite of tools to easily create Microsoft Azure cloud-enabled applications. You can configure,
build, debug, package, and deploy Azure apps and services directly from the Visual Studio integrated
development environment (IDE). To get the Azure tools and project templates, select the Azure development
workload when you install Visual Studio.

In Visual Studio, use Cloud Explorer to view and manage your Azure-based cloud resources. Cloud resources
might include virtual machines (VMs), tables, and SQL databases. Cloud Explorer shows the Azure resources in
all the accounts under the Azure subscription you're signed into. If an operation requires the Azure portal,
Cloud Explorer has links to the place in the portal you need to go.
IMPORTANT
The Cloud Explorer window is retired in Visual Studio 2022. For more information, see Manage the resources associated
with your Azure accounts in Visual Studio Cloud Explorer.
Use the Azure portal to access Azure resources as necessary. You can continue to use the Azure node of Server Explorer in
previous versions of Visual Studio.

You can use Azure services for your apps by adding Connected Ser vices , such as:
Active Directory connected service, to use Azure Active Directory (Azure AD) accounts to connect to web
apps
Azure Storage connected service for blob storage, queues, and tables
Key Vault connected service to manage secrets for web apps
The available Connected Ser vices depend on your project type. Add a service by right-clicking the project in
Solution Explorer and choosing Add > Connected Ser vice .
On the Connected Ser vices screen, select the link or the plus sign to Add a ser vice dependency . On the
Add dependency screen, select the service you want to add, and follow the screens to connect to your Azure
subscription and service.

For more information, see Move to the cloud With Visual Studio and Azure.

Create web apps


Visual Studio can help you write apps for the web. You can create web apps by using ASP.NET, Node.js, Python,
JavaScript, and TypeScript. Visual Studio supports many web frameworks, such as Angular, jQuery, and Express.
ASP.NET Core and .NET Core run on Windows, Mac, and Linux operating systems. ASP.NET Core is a major
update to MVC, WebAPI, and SignalR. ASP.NET Core is designed from the ground up to provide a lean and
composable .NET stack for building modern cloud-based web apps and services.
For more information, see Modern web tooling.

Build cross-platform apps and games


Visual Studio can build apps and games for macOS, Linux, and Windows, and for Android, iOS, and other mobile
devices. With Visual Studio, you can build:
.NET Core apps that run on Windows, macOS, and Linux.
Mobile apps for iOS, Android, and Windows in C# and F# by using Xamarin.
2D and 3D games in C# by using Visual Studio Tools for Unity.
Native C++ apps for iOS, Android, and Windows devices. Share common code in iOS, Android, and
Windows libraries by using C++ for cross-platform development.

Connect to databases
Ser ver Explorer helps you browse and manage server instances and assets locally, remotely, and on Azure,
Microsoft 365, Salesforce.com, and websites. To open Ser ver Explorer , choose View > Ser ver Explorer . For
more information on using Server Explorer, see Add new connections.
SQL Ser ver Object Explorer provides a view of your database objects, similar to SQL Server Management
Studio. With SQL Server Object Explorer, you can do light-duty database administration and design work.
Examples include editing table data, comparing schemas, and executing queries by using contextual menus.

To open SQL Ser ver Object Explorer , select its icon at the top of the Ser ver Explorer window, or select
View > SQL Ser ver Object Explorer from the Visual Studio top menu.
SQL Server Data Tools (SSDT) is a powerful development environment for SQL Server, Azure SQL Database, and
Azure SQL Data Warehouse. With SSDT, you can build, debug, maintain, and refactor databases. You can work
with a database project, or directly with a connected database instance on- or off-premises. To get SSDT, use the
Visual Studio Installer to install the Data storage and processing workload.

Debug, test, and improve your code


When you write code, you should run it and test it for bugs and performance. With Visual Studio's debugging
system, you can debug code running in your local project, on a remote device, or on a device emulator. Step
through code one statement at a time, and inspect variables as you go. Or set breakpoints that are only hit when
a specified condition is true. You can manage debug options in the code editor itself, so you don't have to leave
your code.
For more information about debugging in Visual Studio, see First look at the debugger.
To improve app performance, check out the Visual Studio profiling feature.
Visual Studio offers testing options like unit testing, Live Unit Testing, IntelliTest, and load and performance
testing. Visual Studio also has advanced code analysis capabilities to find design, security, and other flaws.

Deploy your finished application


Visual Studio has tools to deploy your app to users or customers through the Microsoft Store, a SharePoint site,
or InstallShield or Windows Installer technologies. You can access all these options through the Visual Studio
IDE. For more information, see Deploy applications, services, and components.
Manage your source code and collaborate with others
In Visual Studio, you can manage your source code in Git repos hosted by any provider, including GitHub. You
can also browse for an Azure DevOps Server to connect to, too.
For full details, see the Git experience in Visual Studio page and the Visual Studio version control documentation
navigation page. And, for a step-by-step tutorial on how to connect to a Git or Azure DevOps repository by
using Visual Studio, see the Open a project from a repo page.

TIP
We continue to build out the Git feature set and iterate on it based on your feedback. For more info about a recent
feature update along with a link to survey where you can share your feedback on it, see the Multi-repo support in Visual
Studio blog post.

How you open a project from a GitHub repo by using Visual Studio 2019 depends on which version you have.
Specifically, if you've installed version version 16.8 or later, there's a new, more fully integrated Git experience
in Visual Studio available to you. For more information, see the Visual Studio version control documentation
page.
And, for a step-by-step tutorial on how to connect to a Git or Azure DevOps repository by using Visual Studio,
see the Open a project from a repo page.

Next steps
If Visual Studio doesn't have the exact functionality you need, you can add it. Personalize the IDE based on
your workflow and style, add support for external tools that aren't integrated with Visual Studio, and
modify existing functionality to increase your productivity. For the latest version of the Visual Studio
Extensibility Tools (VS SDK), see Visual Studio SDK.
You can use the .NET Compiler Platform Roslyn to write your own code analyzers and code generators.
Find everything you need at Roslyn.
Find existing extensions for Visual Studio created by Microsoft developers and the Visual Studio
development community.
To learn more about extending Visual Studio, see Extend Visual Studio IDE.

See also
Visual Studio IDE overview
What's new in Visual Studio 2017
What's new in Visual Studio 2019
What's new in Visual Studio 2022
Tutorial: Create a simple Visual Basic (VB) console
app
6/24/2022 • 9 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This article shows how you'll use Visual Studio to create a simple Visual Basic application, a console app. In this
app, you ask the user for their name, and then display it back with the current time. You'll also explore some
features of the Visual Studio integrated development environment (IDE), including source control in Git. Visual
Basic is a type-safe programming language that's designed to be easy to learn. A console app takes input and
displays output in a command-line window, also known as a console.
In this tutorial, you learn how to:
Create a Visual Studio project
Run the default application
Add code to ask for user input
Extra credit: Add two numbers
Add Git source control
Clean up resources

Prerequisites
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

Create a project
First, you'll create a Visual Basic app project. The default project template includes all the files you'll need for a
runnable app.

NOTE
Some of the screenshots in this tutorial use the dark theme. If you aren't using the dark theme but would like to, see the
Personalize the Visual Studio IDE and Editor page to learn how.

1. Open Visual Studio 2019.


2. In the start window, choose Create a new project .
3. In the Create a new project window, choose Visual Basic from the Language list. Next, choose
Windows from the Platform list and Console from the project types list.
After you apply these language, platform, and project type filters, choose the Console Application
template, and then choose Next .
NOTE
If you do not see the Console Application template, you can install it from the Create a new project window.
In the Not finding what you're looking for? message, choose the Install more tools and features link.

Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload.

After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work.
Next, choose Continue to install the workload. Then, return to step 2 in this Create a project procedure.

4. In the Configure your new project window, enter WhatIsYourName in the Project name box. Then,
choose Next .

5. In the Additional information window, .NET 5.0 (Current) should already be selected for your target
framework. If not, select .NET 5.0 (Current) . Then, choose Create .
Visual Studio opens your new project.
1. Open Visual Studio.
2. On the start window, choose Create a new project .

3. In the Create a new project window, choose Visual Basic from the Language list. Next, choose
Windows from the Platform list and Console from the Project types list.
After you apply these language, platform, and project type filters, choose the Console App template, and
then choose Next .
NOTE
If you do not see the Console App template, you can install it from the Create a new project window. In the
Not finding what you're looking for? message, choose the Install more tools and features link.

Then, in the Visual Studio Installer, choose the .NET desktop development workload.

After that, choose the Modify button in the Visual Studio Installer. You might be prompted to save your work.
Next, choose Continue to install the workload. Then, return to step 2 in this Create a project procedure.

4. In the Configure your new project window, enter WhatIsYourName in the Project name box. Then,
choose Next .
5. In the Additional information window, .NET 6.0 (Long-term suppor t) should already be selected
for your target framework. If not, select .NET 6.0 (Long-term suppor t) . Then, choose Create .

Visual Studio opens your new project.

Run the app


After you select your Visual Basic project template and name your project, Visual Studio creates a Program.vb
file. The default code calls the WriteLine method to display the literal string "Hello World!" in the console
window.
There are two ways to run this code, inside Visual Studio in debug mode, and from your computer as a regular
standalone app.
Run the app in debug mode

1. Select the WhatIsYourName button or press F5 to run the default code in Debug mode.

2. When the app runs in the Microsoft Visual Studio Debug Console, "Hello World!" displays. Press any key
to close the debug console window and end the app:

1. Select the WhatIsYourName button or press F5 to run the default code in Debug mode.

2. When the app runs in the Microsoft Visual Studio Debug Console, "Hello World!" displays. Press any key
to close the debug console window and end the app:
Run the app as a standalone
To see the output outside of Visual Studio, in a system console window, build and run the executable (.exe file).
1. In the Build menu, choose Build Solution .
2. In Solution Explorer , right-click on WhatIsYourName and choose Open File in File Explorer .
3. In File Explorer , navigate to the bin\Debug\net5.0 directory and run WhatIsYourName.exe .
4. The Main procedure terminates after its single statement executes and the console window closes
immediately. To keep the console visible until the user presses a key, see the next section.
1. In the Build menu, choose Build Solution .
2. In Solution Explorer , right-click on WhatIsYourName and choose Open File in File Explorer .
3. In File Explorer , navigate to the bin\Debug\core6.0 directory and run WhatIsYourName.exe .
4. The Main procedure terminates after its single statement executes and the console window closes
immediately. To keep the console visible until the user presses a key, see the next section.

Add code to ask for user input


Next, you'll add Visual Basic code that prompts you for your name and then displays it along with the current
date and time. In addition, you'll add code that pauses the console window until the user presses a key.
1. Enter the following Visual Basic code after the Sub Main(args As String()) line and before the End Sub
line, replacing the WriteLine line:

Console.Write("Please enter your name: ")


Dim name = Console.ReadLine()
Dim currentDate = DateTime.Now
Console.WriteLine($"Hello, {name}, on {currentDate:d} at {currentDate:t}")
Console.Write("Press any key to continue...")
Console.ReadKey(True)

Write and WriteLine write a string to the console.


ReadLine reads input from the console, in this case a string.
DateTime represents a datetime, and Now returns the current time.
ReadKey() pauses the app and waits for a keypress.

2. Select the WhatIsYourName button or press F5 to build and run your first app in Debug mode.
3. When the debug console window opens, enter your name. Your console window should look similar to
the following screenshot:

4. Press any key to end the app, and then press any key to close the debug console window.
1. Enter the following Visual Basic code after the Sub Main(args As String()) line and before the End Sub
line, replacing the WriteLine line:

Console.Write("Please enter your name: ")


Dim name = Console.ReadLine()
Dim currentDate = DateTime.Now
Console.WriteLine($"Hello, {name}, on {currentDate:d} at {currentDate:t}")
Console.Write("Press any key to continue...")
Console.ReadKey(True)

Write and WriteLine write a string to the console.


ReadLine reads input from the console, in this case a string.
DateTime represents a datetime, and Now returns the current time.
ReadKey() pauses the app and waits for a keypress.

2. Select the WhatIsYourName button or press F5 to build and run your first app in Debug mode.
3. When the debug console window opens, enter your name. Your console window should look similar to
the following screenshot:

4. Press any key to end the app, and then press any key to close the debug console window.
Now that your new code is in the app, build and run the executable (.exe file) in a system console window, as
described previously in Run the app as a standalone. Now when you press a key, the app exits, which closes the
console window.
Extra credit: Add two numbers
This example shows how to read in numbers, rather than a string, and do some arithmetic. Try changing your
code from:

Module Program
Sub Main(args As String())
Console.Write("Please enter your name: ")
Dim name = Console.ReadLine()
Dim currentDate = DateTime.Now
Console.WriteLine($"Hello, {name}, on {currentDate:d} at {currentDate:t}")
Console.Write("Press any key to continue...")
Console.ReadKey(True)
End Sub
End Module

to:

Module Program
Public num1 As Integer
Public num2 As Integer
Public answer As Integer
Sub Main(args As String())
Console.Write("Type a number and press Enter")
num1 = Console.ReadLine()
Console.Write("Type another number to add to it and press Enter")
num2 = Console.ReadLine()
answer = num1 + num2
Console.WriteLine("The answer is " & answer)
Console.Write("Press any key to continue...")
Console.ReadKey(True)
End Sub
End Module

And then run the updated app as described under "Run the app".

Add Git source control


Now that you've created an app, you might want to add it to a Git repository. Visual Studio makes that process
easy with Git tools you can use directly from the IDE.

TIP
Git is the most widely used modern version control system, so whether you're a professional developer or you're learning
how to code, Git can be very useful. If you're new to Git, the https://git-scm.com/ website is a good place to start. There,
you can find cheat sheets, a popular online book, and Git Basics videos.

To associate your code with Git, start by creating a new Git repository where your code is located:
1. In the status bar at the bottom-right corner of Visual Studio, select Add to Source Control , and then
select Git .

2. In the Create a Git repositor y dialog box, sign in to GitHub.


The repository name auto-populates based on your folder location. Your new repository is private by
default, which means you're the only one who can access it.

TIP
Whether your repository is public or private, it's best to have a remote backup of your code stored securely on
GitHub. Even if you aren't working with a team, a remote repository makes your code available to you from any
computer.

3. Select Create and Push .


After you create your repository, you see status details in the status bar.

The first icon with the arrows shows how many outgoing/incoming commits are in your current branch.
You can use this icon to pull any incoming commits or push any outgoing commits. You can also choose
to view these commits first. To do so, select the icon, and then select View Outgoing/Incoming .
The second icon with the pencil shows the number of uncommitted changes to your code. You can select
this icon to view those changes in the Git Changes window.
To learn more about how to use Git with your app, see the Visual Studio version control documentation.

Clean up resources
If you're not going to continue to use this app, delete the project.
1. In Solution Explorer , right-click on WhatIsYourName to open the context menu for your project. Then,
select Open Folder in File Explorer .
2. Close Visual Studio.
3. In the File Explorer dialog, go up two levels of folders.
4. Right-click on the WhatIsYourName folder and select Delete .

Next steps
Congratulations on completing this tutorial! To learn more, see the following tutorial.
Build a library with Visual Basic and the .NET Core SDK in Visual Studio

See also
Visual Basic language walkthroughs
Visual Basic language reference
IntelliSense for Visual Basic code files
Tutorial: Create a WPF application with Visual Basic
6/24/2022 • 6 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial, you'll create an application using Visual Basic in the Visual Studio integrated development
environment (IDE). Your program will use the Windows Presentation Foundation (WPF) UI framework. Use this
tutorial to become familiar with many of the tools, dialog boxes, and designers that you can use in Visual Studio.
In this tutorial, you learn how to:
Create the project
Configure window and add text
Add buttons and code
Debug and test the application
Debug with breakpoints
Build a release version

Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads page for a free version.
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads page for a free version.

Create the project


When you create an application in Visual Studio, you first create a project. In this tutorial, create a Windows
Presentation Foundation project.
1. Open Visual Studio.
2. On the Create a new project screen, search for "WPF", and select WPF App (.NET Framework) .
Select Next .
3. Give the project a name, HelloWPFApp, and select Create .
Visual Studio creates the HelloWPFApp project and solution. Solution Explorer shows the various files.

The WPF Designer shows a design view and a XAML view of MainWindow.xaml in a split view.
1. Open Visual Studio.
2. On the start window, choose Create a new project .
3. On the Create a new project window, search for "WPF" and select Visual Basic in the All languages
drop-down list. Choose WPF App (.NET Framework) , and then choose Next .

4. Give the project a name, HelloWPFApp , and select Create .


Visual Studio creates the HelloWPFApp project and solution. Solution Explorer shows the various files.
The WPF Designer shows a design view and a XAML view of MainWindow.xaml in a split view.

NOTE
For more information about eXtensible Application Markup Language (XAML), see XAML overview for WPF.

Configure window and add text


Using the Proper ties window, you can display and change options for project items, controls, and other items.
1. In Solution Explorer , open the MainWindow.xaml.
2. In the XAML view, change the value of the Window.Title property from Title="MainWindow" to
Title="Greetings".
3. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see it, select View > Toolbox
from the menu bar or Ctrl +Alt +X .
4. Either expand Common WPF Controls or enter Text in the search bar to find TextBlock .

5. Select the TextBlock item and drag it to the window on the design surface. You can move the TextBlock
control by dragging it. Use the guidelines to place the control.
The XAML markup should look like the following example:

<TextBlock HorizontalAlignment="Left" Margin="381,100,0,0" TextWrapping="Wrap" Text="TextBlock"


VerticalAlignment="Top"/>

6. In the XAML view, locate the markup for the TextBlock and change the Text attribute:

Text="Select a message option and then choose the Display button."

Center the TextBlock again if necessary


7. Save your app by choosing the Save All toolbar button. Alternatively, to save your app, choose File >
Save All from the menu bar, or press Ctrl +Shift +S . It's a best practice to save early and often.

Add buttons and code


Your application uses two radio buttons and a button. Use these steps to add them. You'll add Visual Basic code
to the button. That code refers to the radio button selection.
1. In the Toolbox , find RadioButton .

2. Add two RadioButton controls to the design surface by selecting the RadioButton item and dragging it
to the design surface. Move the buttons by selecting them and using the arrow keys. Place the buttons
side by side under the TextBlock control.
3. In the Proper ties window for the left RadioButton control, change the Name property at the top of the
Proper ties window to HelloButton.

4. In the Proper ties window for the right RadioButton control, change the Name property to
GoodbyeButton.
5. Update the Content attribute for HelloButton and GoodbyeButton to "Hello" and "Goodbye" in the
XAML.

<Grid>
<TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a
message option and then choose the Display button." VerticalAlignment="Top"/>
<RadioButton x:Name="HelloButton" Content="Hello" HorizontalAlignment="Left"
Margin="297,161,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left"
Margin="488,161,0,0" VerticalAlignment="Top"/>
</Grid>

6. In the XAML view, locate the markup for HelloButton and add an IsChecked attribute:
IsChecked="True"

The IsChecked attribute with the value True means that HelloButton is checked by default. This setting
means that the radio button is always selected, even when the program starts.
7. In the Toolbox , find the Button control, and then drag a button to the design surface under the
RadioButton controls.
8. In the XAML view, change the value of Content for the Button control from Content="Button" to
Content="Display" .

<Button Content="Display" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"


Margin="215,204,0,0"/>

Your window should resemble the following image.

9. On the design surface, double-click the Display button.


Greetings.xaml.vb opens, with the cursor in the Button_Click event.

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)

End Sub

10. Add the following code:

If HelloButton.IsChecked = True Then


MessageBox.Show("Hello.")
ElseIf GoodbyeButton.IsChecked = True Then
MessageBox.Show("Goodbye.")
End If

Debug and test the application


Next, you'll debug the application to look for errors and test that both message boxes appear correctly. To see
how this process works, the first step deliberately introduces an error into the program.
1. In Solution Explorer , right-click on MainWindow.xaml and choose Rename . Rename the file to
Greetings.xaml.
2. Start the debugger by pressing F5 or selecting Debug , then Star t Debugging .
A Break Mode window appears, and the Output window indicates that an exception has occurred.

3. Stop the debugger by choosing Debug > Stop Debugging .


You renamed MainWindow.xaml to Greetings.xaml at the start of this section. The code still refers to
MainWindow.xaml as the startup URI for the application, so the project can't start.
4. In Solution Explorer , open the Application.xaml file.
5. Change StartupUri="MainWindow.xaml" to StartupUri="Greetings.xaml"

6. Start the debugger again (press F5 ). You should now see the Greetings window of your application.
7. Select Hello and the Display button, and then Goodbye and the Display button. Use the close icon in
the upper right corner to stop debugging.
For more information, see Build a WPF application (WPF) and Debug WPF.

Debug with breakpoints


You can test the code during debugging by adding some breakpoints.
1. Open Greetings.xaml.vb, and select the following line: MessageBox.Show("Hello.")

2. Add a breakpoint by pressing F9 or selecting Debug , then Toggle Breakpoint .


A red circle appears next to the line of code in the left margin of the editor window.
3. Select the following line: MessageBox.Show("Goodbye.") .
4. Press the F9 key to add a breakpoint, and then press F5 to start debugging.
5. In the Greetings window, select the Hello button, and then select Display .
The line MessageBox.Show("Hello.") is highlighted in yellow. At the bottom of the IDE, the Autos , Locals ,
and Watch windows are docked together on the left side. The Call Stack , Breakpoints , Exception
Settings , Command , Immediate , and Output windows are docked together on the right side.
6. On the menu bar, choose Debug > Step Out .
The application starts again. A dialog box with the word "Hello" appears.
7. Choose the OK button to close the dialog box.
8. In the Greetings window, choose the Goodbye radio button, and then choose the Display button.
The line MessageBox.Show("Goodbye.") is highlighted in yellow.
9. Choose the F5 key to continue debugging. When the dialog box appears, choose OK to close the dialog
box.
10. Close the application window to stop debugging.
11. On the menu bar, choose Debug > Disable All Breakpoints .

Build a release version


Now that you've verified that everything works, you can prepare a release build of your application.
1. Select Build > Clean solution to delete intermediate files and output files that were created during
previous builds.
2. Change the build configuration for HelloWPFApp from Debug to Release by using the dropdown
control on the toolbar.
3. Select Build > Build Solution .
Congratulations on completing this tutorial! You can find the .exe you built under your solution and project
directory (...\HelloWPFApp\HelloWPFApp\bin\Release).

Next steps
Advance to the next article to learn how to create a Windows Forms app in Visual Studio with Visual Basic.
Create a Windows Forms app

See also
For more information about Visual Studio, see these resources:
What's new in Visual Studio 2019
Productivity tips
What's new in Visual Studio 2022
Productivity tips
Tutorial: Create a WinForms app with Visual Basic
6/24/2022 • 4 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial, you'll create a Visual Basic application that has a Windows Forms user interface. The Visual Studio
integrated development environment (IDE) includes all the tools you need to create a Windows Forms app.
In this tutorial, you learn how to:
Create a project
Add a button to the form
Add a label and code
Run the application

Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads page for a free version.
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads page for a free version.

Create a project
Create a Visual Basic application project. The project type comes with all the template files you'll need, before
you've even added anything.
1. Open Visual Studio.
2. On the start window, choose Create a new project .

3. On the Create a new project window, select the Windows Forms App (.NET Framework) template
for Visual Basic.
You can refine your search to quickly get to the template you want. For example, enter Windows Forms
App in the search box. Next, select Visual Basic from the Language list, and then Windows from the
Platform list.

NOTE
If you don't see the Windows Forms App (.NET Framework) template, you can install it from the Create a
new project window. In the Not finding what you're looking for? message, choose the Install more tools
and features link.

Next, in the Visual Studio Installer, choose the .NET desktop development workload.

After that, select Modify in the Visual Studio Installer. You might be prompted to save your work.

4. In the Configure your new project window, enter HelloWorld as the Project name . Then, select
Create .
Visual Studio opens your new project.
1. Open Visual Studio.
2. On the start window, choose Create a new project .

3. On the Create a new project window, select the Windows Forms App (.NET Framework) template
for Visual Basic.
You can refine your search to quickly get to the template you want. For example, enter Windows Forms
App in the search box. Next, select Visual Basic from the Language list, and then Windows from the
Platform list.
NOTE
If you don't see the Windows Forms App (.NET Framework) template, you can install it from the Create a
new project window. In the Not finding what you're looking for? message, choose the Install more tools
and features link.

Next, in the Visual Studio Installer, choose the .NET desktop development workload.

After that, select Modify in the Visual Studio Installer. You might be prompted to save your work.

4. In the Configure your new project window, enter HelloWorld as the Project name . Then, select
Create .
Visual Studio opens your new project.

Add a button to the form


After you select your Visual Basic project template and name your file, Visual Studio opens a form for you. A
form is a Windows user interface. You'll create a "Hello World" application by adding controls to the form.
1. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see it, select View > Toolbox
from the menu bar or Ctrl +Alt +X .

If you want, select the Pin icon to dock the Toolbox window.
2. Select the Button control and then drag it onto the form.
3. In the Appearance section of the Proper ties window, for Text , type Click this, and then press Enter .

If you don't see the Proper ties window, you can open it from the menu bar. Select View > Proper ties
Window or press F4 .
4. In the Design section of the Proper ties window, change the name from Button1 to btnClickThis, and
then press Enter .
NOTE
If you've alphabetized the list in the Proper ties window, Button1 appears in the (DataBindings) section,
instead.

Add a label and code


Now that you've added a button control to create an action, add a label control to send text to.
1. Select the Label control in the Toolbox window, and then drag it onto the form. Place it beneath the
Click this button.
2. In either the Design section or the (DataBindings) section of the Proper ties window, change the name
Label1 to lblHelloWorld, and then press Enter .
3. In the Form1.vb [Design] window, double-click the Click this button to open the Form1.vb window.
Another option is to expand Form1.vb in Solution Explorer , and then select Form1 .
4. In the Form1.vb window, between the Private Sub and End Sub lines, enter lblHelloWorld.Text = "Hello
World!" as shown in the following screenshot:

Run the application


Your application is ready to build and run.
1. Select Star t to run the application.
Several things happen. In the Visual Studio IDE, the Diagnostics Tools window opens, and an Output
window opens. Outside of the IDE, a Form1 dialog box appears. It includes your Click this button and
text that says Label1 .
2. Select the Click this button in the Form1 dialog box.

The Label1 text changes to Hello World! .


3. Close the Form1 dialog box to stop running the app.

Next steps
To learn more about Windows Forms, continue with the following tutorial:
Tutorial: Create a picture viewer

See also
More Visual Basic tutorials
C# tutorials
C++ tutorials
Tutorial: Create a picture viewer Windows Forms
app in Visual Studio
6/24/2022 • 6 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of three tutorials, you'll create a Windows Forms application that loads a picture and displays it. The
Visual Studio Integrated Design Environment (IDE) provides the tools you need to create the app. To learn more,
see Welcome to the Visual Studio IDE.
In this first tutorial, you learn how to:
Create a Visual Studio project that uses Windows Forms
Add a layout element
Run your application

Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads page for a free version.

Create your Windows Forms project


When you create a picture viewer, the first step is to create a Windows Forms App project.
1. Open Visual Studio.
2. On the start window, select Create a new project .

3. On the Create a new project window, search for Windows Forms. Then select Desktop from the
Project type list.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then
select Next .

NOTE
If you don't see the Windows Forms App (.NET Framework) template, you can install it from the Create a
new project window. In the Not finding what you're looking for? message, select the Install more tools
and features link.

Next, in Visual Studio Installer, select .NET desktop development .

Select Modify in the Visual Studio Installer. You might be prompted to save your work. Next, select Continue to
install the workload.

5. In the Configure your new project window, name your project PictureViewer, then select Create .
1. Open Visual Studio.
2. On the start window, select Create a new project .
3. On the Create a new project window, search for Windows Forms. Then select Desktop from the
Project type list.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then
select Next .
NOTE
If you don't see the Windows Forms App (.NET Framework) template, you can install it from the Create a
new project window. In the Not finding what you're looking for? message, select the Install more tools
and features link.

Next, in Visual Studio Installer, select .NET desktop development .

Select Modify in the Visual Studio Installer. You might be prompted to save your work. Next, select Continue to
install the workload.

5. In the Configure your new project window, name your project PictureViewer, then select Create .
Visual Studio creates a solution for your app. A solution is a container for all of the projects and files needed by
your app.
At this point, Visual Studio displays an empty form in the Windows Form Designer .

Add a layout element


Your picture viewing app contains a picture box, a checkbox, and four buttons, which you'll add in the next
tutorial. The layout element controls their location on the form. This section shows you how to change the title
of your form, resize the form, and add a layout element.
1. In your project, select the Windows Forms Designer. The tab reads Form1.cs [Design] for C# or
Form1.vb [Design] for Visual Basic.
2. Select anywhere in Form1 .
3. The Proper ties window now displays properties for the form. The Proper ties window is usually in the
lower right of Visual Studio. This section controls various properties, such as foreground and background
color, title text that appears at the top of the form, and the size of the form.
If you don't see Proper ties , select View > Proper ties Window .
4. Find the Text property in the Proper ties window. Depending on how the list is sorted, you might need
to scroll down. Enter the value Picture Viewer, and then choose Enter .
Your form now has the text Picture Viewer in its title bar.

NOTE
You can display properties by category or alphabetically. Use the buttons on the Proper ties window to switch
back and forth.

5. Select the form, again. Select the form's lower-right drag handle. The handle is a small white square in the
lower-right corner of the form.
Drag the handle to resize the form so the form is wider and a bit taller. If you look at the Proper ties
window, the Size property has changed. You can also change the size of the form by changing the Size
property.
6. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see it, select View > Toolbox
from the menu bar or Ctrl +Alt +X .
7. Select the small triangle symbol next to Containers to open the group.

8. Double-click TableLayoutPanel in the Toolbox . You can also drag a control from the toolbox onto the
form. The TableLayoutPanel control appears in your form.
NOTE
After you add your TableLayoutPanel, if a window appears inside your form with the title TableLayoutPanel
Tasks , click anywhere inside the form to close it.

9. Select the TableLayoutPanel . You can verify what control is selected by looking at the Proper ties
window.

10. With the TableLayoutPanel selected, find the Dock property, which has the value None . Select the
dropdown arrow and then select Fill , which is the large button in the middle of the dropdown menu.

Docking refers to how a window is attached to another window or area.


The TableLayoutPanel now fills the entire form. If you resize the form again, the TableLayoutPanel stays
docked, and resizes itself to fit.
11. In the form, select the TableLayoutPanel. In the upper-right corner, there's a small black triangle button.
Select the triangle to display the control's task list.

12. Select Edit Rows and Columns to display the Column and Row Styles dialog box.
13. Select Column1 and set its size to 15 percent. Be sure the Percent button is selected.
14. Select Column2 and set it to 85 percent.
15. From Show at the top of the Column and Row Styles dialog box, select Rows . Set Row1 to 90 percent
and Row2 to 10 percent. Select OK to save your changes.
Your TableLayoutPanel now has a large top row, a small bottom row, a small left column, and a large right
column.

Your layout is complete.

NOTE
Before you run your application, save your app by choosing the Save All toolbar button. Alternatively, to save your app,
choose File > Save All from the menu bar, or press Ctrl+Shift +S. It's a best practice to save early and often.

Run your app


When you create a Windows Forms App project, you build a program that runs. At this stage, your Picture
Viewer app doesn't do much. For now, it displays an empty window that shows Picture Viewer in the title bar.
To run the app, follow these steps.
1. Use one of the following methods:
Select the F5 key.
On the menu bar, select Debug > Star t Debugging .
On the toolbar, select the Star t button.
Visual Studio runs your app. A window with the title Picture Viewer appears.

Look at the Visual Studio IDE toolbar. More buttons appear on the toolbar when you run an application.
These buttons let you do things like stop and start your app, and help you track down any errors.

2. Use one of the following methods to stop your app:


On the toolbar, select the Stop Debugging button.
On the menu bar, select Debug > Stop Debugging .
From the keyboard, enter Shift +F5 .
Select X in the upper corner of the Picture Viewer window.
When you run your app from inside the Visual Studio IDE, it's called debugging. You run your application
to find and fix bugs. You follow the same procedure to run and debug other programs. To learn more
about debugging, see First look at the debugger.

Next steps
Advance to the next tutorial to learn how to add controls to your Picture Viewer program.
Tutorial part 2: Add controls to your Picture Viewer
Tutorial: Add UI controls to the picture viewer
Windows Forms app in Visual Studio
6/24/2022 • 5 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of three tutorials, you'll create a Windows Forms application that loads a picture and displays it. The
Visual Studio Integrated Design Environment (IDE) provides the tools you need to create the app. To learn more,
see Welcome to the Visual Studio IDE.
This program has a picture box, a checkbox, and several buttons, which you use to control the application. This
tutorial shows you how to add these controls.
In this second tutorial, you learn how to:
Add controls to your application
Add buttons in a layout panel
Change control names and locations
Add dialog components

Prerequisites
This tutorial builds on the previous tutorial, Create a picture viewer application. If you haven't done that tutorial,
go through that one first.

Add controls to your application


The Picture Viewer app uses a PictureBox control to display a picture. It uses a checkbox and several buttons to
manage the picture and background and to close the app. You'll add the PictureBox and a checkbox from the
Toolbox in the Visual Studio IDE.
1. Open Visual Studio. Your Picture Viewer project appears under Open recent .
2. In the Windows Forms Designer , select the TableLayoutPanel you added in the previous tutorial. Check
that tableLayoutPanel1 appears in the Proper ties window.
3. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see it, select View > Toolbox
from the menu bar or Ctrl +Alt +X . In the toolbox, expand Common Controls .
4. Double-click PictureBox to add a PictureBox control to your form. Visual Studio IDE adds the PictureBox
control to the first empty cell of the TableLayoutPanel.
5. Choose the new PictureBox control to select it, and then select the black triangle on the new PictureBox
control to display its task list.
6. Select Dock in Parent Container , which sets the PictureBox Dock property to Fill . You can see that
value in the Proper ties window.
7. In the Proper ties window for the PictureBox, set the ColumnSpan property to 2 . The PictureBox now
fills both columns.
8. Set the BorderStyle property to Fixed3D .
9. In the Windows Forms Designer , select TableLayoutPanel . Then, in the Toolbox , double-click the
CheckBox item to add a new CheckBox control. Your PictureBox takes up the first two cells in the
TableLayoutPanel, so the CheckBox control is added to the lower-left cell.
10. Choose the Text property and enter Stretch .

Add buttons in a layout panel


The controls so far have been added to the TableLayoutPanel. These steps show you how to add four buttons to
a new layout panel in the TableLayoutPanel.
1. Select the TableLayoutPanel on the form. Open the Toolbox , select Containers . Double-click
FlowLayoutPanel to add a new control to the last cell of the TableLayoutPanel.
2. Set the FlowLayoutPanel's Dock property to Fill . You can set this property by selecting the black triangle,
then selecting Dock in parent container .
A FlowLayoutPanel is a container that arranges other controls in a row, one after another.
3. Select the new FlowLayoutPanel, and then open the Toolbox and select Common Controls . Double-
click the Button item to add a button control called button1 .
4. Double-click Button again to add another button. The IDE calls the next one button2 .
5. Add two more buttons this way. Another option is to select button2 , and then select Edit > Copy or
press Ctrl +C . Next, choose Edit > Paste from the menu bar or press Ctrl +V . To paste a copy of your
button. Now paste it again. Notice that the IDE adds button3 and button4 to the FlowLayoutPanel.
6. Select the first button and set its Text property to Show a picture .
7. Set the Text properties of the next three buttons to Clear the picture , Set the background color , and
Close .
8. To size the buttons and arrange them, select the FlowLayoutPanel. Set the FlowDirection property to
RightToLeft .
The buttons should align themselves to the right side of the cell, and reverse their order so that the Show
a picture button is on the right. You can drag the buttons around the FlowLayoutPanel to arrange them
in any order.
9. Choose the Close button to select it. Then, to choose the rest of the buttons at the same time, press and
hold the Ctrl key and choose them, too.
10. In the Proper ties window, set the AutoSize property to True . The buttons resize to fit their text.
You can run your program to see how the controls look. Select the F5 key, select Debug > Star t Debugging ,
or select the Star t button. The buttons that you added don't do anything, yet.

Change control names


There are four buttons on your form, named button1 , button2 , button3 , and button4 in C#. In Visual Basic,
the default first letter of any control name is capitalized, so the buttons are named Button1 , Button2 , Button3 ,
and Button4 . Use these steps to give them more informative names.
1. On the form, choose the Close button. If you still have all the buttons selected, choose Esc to cancel the
selection.
2. In the Proper ties window, look for (Name) . Change the name to closeButton .

The IDE doesn't accept names that contain spaces.


3. Rename the other three buttons to backgroundButton , clearButton , and showButton . You can verify
the names by choosing the control selector drop-down list in the Proper ties window. The new button
names appear.
You can change the name of any control, such as the TableLayoutPanel or checkbox.

Add dialog components


Your app can open picture files and choose a background color by using components. A component is like a
control. You use the Toolbox to add a component to your form. You set its properties using the Proper ties
window.
Unlike a control, adding a component to your form doesn't add a visible item. Instead, it provides certain
behaviors that you can trigger with code. For instance, it's a component that opens an Open File dialog box.
In this section, you add an OpenFileDialog component and a ColorDialog component to your form.
1. Select the Windows Forms Designer (Form1.cs [Design] ). Then open the Toolbox and select the
Dialogs group.
2. Double-click OpenFileDialog to add a component called openFileDialog1 to your form.
3. Double-click ColorDialog to add a component called colorDialog1 . The components appear at the
bottom of Windows Forms Designer as icons.
4. Choose the openFileDialog1 icon and set two properties:
Set the Filter property to the following:

JPEG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|BMP Files (*.bmp)|*.bmp|All files (*.*)|*.*

Set the Title property to the following: Select a picture file


The Filter property settings specify the types that the Select a picture dialog box displays.

Next steps
Advance to the next tutorial to learn how to add code to your application.
Tutorial part 3: Add code to your Picture Viewer
Tutorial: Add code to the picture viewer Windows
Forms app in Visual Studio
6/24/2022 • 7 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of three tutorials, you'll create a Windows Forms application that loads a picture and displays it. The
Visual Studio Integrated Design Environment (IDE) provides the tools you need to create the app. To learn more,
see Welcome to the Visual Studio IDE.
Controls use C# or Visual Basic code to take the actions associated with them.
In this third tutorial, you learn how to:
Add event handlers for your controls
Write code to open a dialog box
Write code for the other controls
Run your application

Prerequisites
This tutorial builds on the previous tutorials, Create a picture viewer application and Add UI controls to the
picture viewer. If you haven't done those tutorials, go through them first.

Add event handlers for your controls


In this section, add event handlers for the controls that you added in the second tutorial, Add controls to a
picture viewer application. Your application calls an event handler when an action takes place, such as selecting a
button.
1. Open Visual Studio. Your Picture Viewer project appears under Open recent .
2. In the Windows Forms Designer , double-click the Show a picture button. You can instead select the
Show a picture button on the form, and then press Enter .
The Visual Studio IDE opens a tab in the main window. For C#, the tab is named Form1.cs . If you're using
Visual Basic, the tab is named Form1.vb .
This tab displays the code file behind the form.
NOTE
Your Form1.vb tab might display showButton as ShowButton .

3. Focus on this part of the code.


C#
VB

private void ShowButton_Click(object sender, EventArgs e)


{
}

IMPORTANT
Use the programming language control at the top right of this page to view either the C# code snippet or the
Visual Basic code snippet.

4. Choose the Windows Forms Designer tab again, and then double-click the Clear the picture button
to open its code. Repeat for the remaining two buttons. Each time, the Visual Studio IDE adds a new
method to the form's code file.
5. Double-click the CheckBox control in Windows Forms Designer to add a checkBox1_CheckedChanged()
method. When you select or clear the check box, it calls this method.
The following snippet shows the new code that you see in the code editor.

C#
VB

private void clearButton_Click(object sender, EventArgs e)


{
}

private void backgroundButton_Click(object sender, EventArgs e)


{
}

private void closeButton_Click(object sender, EventArgs e)


{
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)


{
}

Methods, including event handlers, can have any name that you want. When you add an event handler with the
IDE, it creates a name based on the control's name and the event being handled.
For example, the Click event for a button named showButton is called showButton_Click() or
ShowButton_Click() . If you want to change a code variable name, right-click the variable in the code and then
choose Refactor > Rename . All instances of that variable in the code are renamed. For more information, see
Rename refactoring.

Write code to open a dialog box


The Show a picture button uses the OpenFileDialog component to display a picture file. This procedure adds
the code used to call that component.
The Visual Studio IDE offers a powerful tool called IntelliSense. As you type, IntelliSense suggests possible code.
1. In Windows Forms Designer , double-click the Show a picture button. The IDE moves your cursor
inside the showButton_Click() or ShowButton_Click() method.
2. Type an i on the empty line between the two braces { } or between Private Sub... and End Sub . An
IntelliSense window opens.

3. The IntelliSense window should highlight the word if . Select the Tab key to insert if .
4. Select true and then type op to overwrite it for C# or Op for Visual Basic.

IntelliSense displays openFileDialog1 .


5. Select Tab to add openFileDialog1.
6. Type a period ( . ) or dot, right after openFileDialog1 . IntelliSense provides all of the OpenFileDialog
component's properties and methods. Start to type ShowDialog and select Tab The ShowDialog() method
will show the Open File dialog box.
7. Add parentheses immediately after the "g" in ShowDialog : () . Your code should be
openFileDialog1.ShowDialog() .

8. For C#, add a space, and then add two equal signs ( == ). For Visual Basic, add a space, and then use a
single equal sign ( = ).
9. Add another space. Use IntelliSense to enter DialogResult.
10. Type a dot to open the DialogResult value in the IntelliSense window. Enter the letter O and choose the
Tab key to insert OK .

NOTE
The first line of code should be complete. For C#, it should be similar to the following.
if (openFileDialog1.ShowDialog() == DialogResult.OK)

For Visual Basic, it should be the following.


If OpenFileDialog1.ShowDialog() = DialogResult.OK Then

11. Add the following line of code.

C#
VB

pictureBox1.Load(openFileDialog1.FileName);

You can copy and paste or use IntelliSense to add it. Your final showButton_Click() method should look
similar to the following code.

C#
VB
private void showButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}

1. Add the following comment to your code.


C#
VB

private void showButton_Click(object sender, EventArgs e)


{
// Show the Open File dialog. If the user clicks OK, load the
// picture that the user chose.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}

It's the best practice to always comment your code. Code comments make it easier to understand and maintain
your code in the future.

Write code for the other controls


If you run your application now, you can select Show a picture . Picture Viewer opens the Open File dialog
box, where you can select a picture to display.
In this section, add the code for the other event handlers.
1. In Windows Forms Designer , double-click the Clear the picture button. Add the code in the braces.

C#
VB

private void clearButton_Click(object sender, EventArgs e)


{
// Clear the picture.
pictureBox1.Image = null;
}

2. Double-click the Set the background color button and add the code in braces.

C#
VB
private void backgroundButton_Click(object sender, EventArgs e)
{
// Show the color dialog box. If the user clicks OK, change the
// PictureBox control's background to the color the user chose.
if (colorDialog1.ShowDialog() == DialogResult.OK)
pictureBox1.BackColor = colorDialog1.Color;
}

3. Double-click the Close button and add the code in braces.

C#
VB

private void closeButton_Click(object sender, EventArgs e)


{
// Close the form.
this.Close();
}

4. Double-click the Stretch checkbox and add the code in braces.

C#
VB

private void checkBox1_CheckedChanged(object sender, EventArgs e)


{
// If the user selects the Stretch check box,
// change the PictureBox's
// SizeMode property to "Stretch". If the user clears
// the check box, change it to "Normal".
if (checkBox1.Checked)
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
else
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
}

Run your application


You can run your application at any time, while you're writing it. After you add the code in the previous section,
the Picture Viewer is complete. As in the previous tutorials, use one of the following methods to run your
application:
Select the F5 key.
On the menu bar, select Debug > Star t Debugging .
On the toolbar, select the Star t button.
A window with the title Picture Viewer appears. Test all the controls.
1. Select the Set the background color button. The Color dialog box opens.
2. Choose a color to set the background color.
3. Select Show a picture to display a picture.

4. Select and unselect Stretch .


5. Select the Clear the picture button to make sure the display clears.
6. Select Close to exit the app.

Next steps
Congratulations! You've completed this series of tutorials. You've done these programming and design tasks in
the Visual Studio IDE:
Created a Visual Studio project that uses Windows Forms
Done layout for the picture viewing application
Added buttons and a checkbox
Added dialog boxes
Added event handlers for your controls
Written C# or Visual Basic code to handle the events
Continue learning with another tutorial series on how to create a timed math quiz.
Tutorial 2: Create a timed math quiz
Tutorial: Create a math quiz WinForms app
6/24/2022 • 8 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you'll build a math quiz. The quiz contains four random math problems that a quiz
taker tries to answer within a specified time.
The Visual Studio integrated development environment (IDE) provides the tools that you need to create the app.
To learn more about this IDE, see Welcome to the Visual Studio IDE.
In this first tutorial, you learn how to:
Create a Visual Studio project that uses Windows Forms.
Add labels, a button, and other controls to a form.
Set properties for the controls.
Save and run your project.

Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads page for a free version.

Create your Windows Forms project


When you create a math quiz, the first step is to create a Windows Forms App project.
1. Open Visual Studio.
2. On the start window, select Create a new project .

3. In the Create a new project window, search for Windows Forms . Then select Desktop from the
Project type list.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then
select Next .

NOTE
If you don't see the Windows Forms App (.NET Framework) template, you can install it from the Create a
new project window. In the Not finding what you're looking for? message, select Install more tools and
features .

Next, in Visual Studio Installer, select .NET desktop development .

Select Modify in Visual Studio Installer. You might be prompted to save your work. Next, select Continue to
install the workload.

5. In the Configure your new project window, name your project MathQuiz , and then select Create .
1. Open Visual Studio.
2. On the start window, select Create a new project .
3. In the Create a new project window, search for Windows Forms . Then select Desktop from the
Project type list.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then
select Next .
NOTE
If you don't see the Windows Forms App (.NET Framework) template, you can install it from the Create a
new project window. In the Not finding what you're looking for? message, select Install more tools and
features .

Next, in Visual Studio Installer, select .NET desktop development .

Select Modify in Visual Studio Installer. You might be prompted to save your work. Next, select Continue to
install the workload.

5. In the Configure your new project window, name your project MathQuiz , and then select Create .
Visual Studio creates a solution for your app. A solution is a container for all the projects and files that your app
needs.

Set form properties


After you select your template and name your file, Visual Studio opens a form for you. This section shows you
how to change some form properties.
1. In your project, select Windows Forms Designer . The designer tab is labeled Form1.cs [Design] for
C# or Form1.vb [Design] for Visual Basic.
2. Select the form, Form1 .
3. The Proper ties window now displays properties for the form. This window is usually in the lower right
corner of Visual Studio. If you don't see Proper ties , select View > Proper ties Window .
4. Find the Text property in the Proper ties window. Depending on how the list is sorted, you might need
to scroll down. Enter the value Math Quiz for the Text value, and then select Enter .
Your form now has the text "Math Quiz" in its title bar.

NOTE
You can display properties by category or alphabetically. Use the buttons on the Proper ties window to switch
back and forth.

5. Change the size of the form to 500 pixels wide by 400 pixels tall.
You can resize the form by dragging its edges or drag handle until the correct size appears as the Size
value in the Proper ties window. The drag handle is a small white square in the lower-right corner of the
form. You can also resize the form by changing the values of the Size property.
6. Change the value of the FormBorderStyle property to Fixed3D , and set the MaximizeBox property to
False .
These values prevent quiz takers from resizing the form.
Create the time remaining box
The math quiz contains a box in the upper-right corner. That box shows the number of seconds that remain in
the quiz. This section shows you how to use a label for that box. You'll add code for the countdown timer in a
later tutorial in this series.
1. On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see the toolbox, select View
> Toolbox from the menu bar or Ctrl +Alt +X .
2. Select the Label control in the Toolbox , and then drag it onto the form.
3. In the Proper ties box, set the following properties for the label:
Set the (Name) to timeLabel .
Change AutoSize to False so that you can resize the box.
Change the BorderStyle to FixedSingle to draw a line around the box.
Set the Size to 200, 30 .
Select the Text property, and then select the Backspace key to clear the Text value.
Select the plus sign (+ ) next to the Font property, and then set the Size to 15.75 .
4. Move the label to the upper-right corner of the form. When blue spacer lines appear, use them to position
the control on the form.
5. Add another Label control from the Toolbox , and then set its font size to 15.75 .
6. Set this label's Text property to Time Left .
7. Move the label so that it lines up to the left of the timeLabel label.

Add controls for the addition problem


The first part of the quiz is an addition problem. This section shows you how to use labels to display that
problem.
1. Add a Label control from the Toolbox to the form.
2. In the Proper ties box, set the following properties for the label:
Set the Text to ? (question mark).
Set AutoSize to False .
Set the Size to 60, 50 .
Set the font size to 18 .
Set TextAlign to MiddleCenter .
Set the Location to 50, 75 to position the control on the form.
Set the (Name) to plusLeftLabel .
3. In the form, select the plusLeftLabel label that you created. Copy the label by selecting either Edit >
Copy or Ctrl +C .
4. Paste the label into the form three times by selecting either Edit > Paste or Ctrl +V three times.
5. Arrange the three new labels so that they are in a row to the right of the plusLeftLabel label.
6. Set the second label's Text property to + (plus sign).
7. Set the third label's (Name) property to plusRightLabel .
8. Set the fourth label's Text property to = (equals sign).
9. Add a NumericUpDown control from the Toolbox to the form. You'll learn more about this kind of
control later.
10. In the Proper ties box, set the following properties for the NumericUpDown control:
Set the font size to 18 .
Set the width to 100 .
Set the (Name) to sum .
11. Line up the NumericUpDown control with the Label controls for the addition problem.

Add controls for the subtraction, multiplication, and division problems


Next, add labels to the form for the remaining math problems.
1. Copy the four Label controls and the NumericUpDown control that you created for the addition problem.
Paste them into the form.
2. Move the new controls to line up below the addition controls.
3. In the Proper ties box, set the following properties for the new controls:
Set the (Name) of the first question-mark label to minusLeftLabel .
Set the Text of the second label to - (minus sign).
Set the (Name) of the second question-mark label to minusRightLabel .
Set the (Name) of the NumericUpDown control to difference .
4. Copy the addition controls, and paste them two more times into the form.
5. For the third row:
Set the (Name) of the first question-mark label to timesLeftLabel .
Set the Text of the second label to × (multiplication sign). You can copy the multiplication sign from
this tutorial and paste it onto the form.
Set the (Name) of the second question-mark label to timesRightLabel .
Set the (Name) of the NumericUpDown control to product .
6. For the fourth row:
Set the (Name) of the first question-mark label to dividedLeftLabel .
Set the Text of the second label to ÷ (division sign). You can copy the division sign from this tutorial
and paste it onto the form.
Set the (Name) of the second question-mark label to dividedRightLabel .
Set the (Name) of the NumericUpDown control to quotient .

Add a start button and set the tab-index order


This section shows you how to add a start button. You'll also specify the tabbing order of the controls. This
ordering determines how the quiz taker moves from one control to the next by using the Tab key.
1. Add a Button control from the Toolbox to the form.
2. In the Proper ties box, set the following properties of the Button:
Set the (Name) to star tButton .
Set the Text to Star t the quiz .
Set the font size to 14 .
Set AutoSize to True , which causes the button to automatically resize to fit the text.
Set the TabIndex to 0 . This value makes the start button the first control to receive the focus.
3. Center the button near the bottom of the form.
4. In the Proper ties box, set the TabIndex property of each NumericUpDown control:
Set the TabIndex of the sum NumericUpDown control to 1 .
Set the TabIndex of the difference NumericUpDown control to 2 .
Set the TabIndex of the product NumericUpDown control to 3 .
Set the TabIndex of the quotient NumericUpDown control to 4 .

Run your app


The math problems don't work yet on your quiz. But you can still run your app to check whether the TabIndex
values function as you expect.
1. Use one of the following methods to save your app:
Select Ctrl +Shift +S .
On the menu bar, select File > Save All .
On the toolbar, select the Save All button.
2. Use one of the following methods to run your app:
Select F5 .
On the menu bar, select Debug > Star t Debugging .
On the toolbar, select the Star t button.
3. Select the Tab key a few times to see how the focus moves from one control to the next.

Next steps
Advance to the next tutorial to add random math problems and an event handler to your math quiz.
Tutorial part 2: Add math problems to a math quiz WinForms app
Tutorial: Add math problems to a math quiz
WinForms app
6/24/2022 • 9 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you'll build a math quiz. The quiz contains four random math problems that a quiz
taker tries to answer within a specified time.
Controls use C# or Visual Basic code. In this second tutorial, you make the quiz challenging by adding code for
math problems that are based on random numbers. You also create a method that's named StartTheQuiz() to
fill in the problems.
In this second tutorial, you learn how to:
Write code to create Random objects to use in math problems.
Add an event handler for the start button.
Write code to start the quiz.

Prerequisites
This tutorial builds on a previous tutorial, Create a math quiz WinForms app. If you haven't completed that
tutorial, go through it first.

Create a random addition problem


1. In your Visual Studio project, select Windows Forms Designer .
2. Select the form, Form1 .
3. On the menu bar, select View > Code . Form1.cs or Form1.vb appears, depending on the programming
language that you're using, so that you can view the code behind the form.
4. Create a Random object by adding a new statement near the top of the code.

C#
VB

public partial class Form1 : Form


{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();
IMPORTANT
Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic
code snippet.

You can use new statements like this one to create buttons, labels, panels, OpenFileDialogs, ColorDialogs,
SoundPlayers, Randoms, and even forms. These items are called objects.
When you run your program, the form is started. The code behind it creates a Random object and names it
randomizer .
Your quiz needs variables to store the random numbers that it creates for each problem. Before using variables,
you declare them, which means listing their names and data types.
1. Add two integer variables to the form, and name them addend1 and addend2 .

NOTE
An integer variable is known as an int in C# or an Integer in Visual Basic. This kind of variable stores a positive or
negative number from -2147483648 through 2147483647 and can store only whole numbers, not decimals.

You use similar syntax to add an integer variable as you did to add the Random object, as the following
code shows.
C#
VB

// Create a Random object called randomizer


// to generate random numbers.
Random randomizer = new Random();

// These integer variables store the numbers


// for the addition problem.
int addend1;
int addend2;

1. Add a method that's named StartTheQuiz() . This method uses the Random object's Next() method to
generate random numbers for the labels. StartTheQuiz() will eventually fill in all the problems and then
start the timer, so add this information to the summary comment. The function should look like the
following code.

C#
VB
/// <summary>
/// Start the quiz by filling in all of the problems
/// and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);

// Convert the two randomly generated numbers


// into strings so that they can be displayed
// in the label controls.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

// 'sum' is the name of the NumericUpDown control.


// This step makes sure its value is zero before
// adding any values to it.
sum.Value = 0;
}

When you use the Next() method with a Random object, such as when you call randomizer.Next(51) , you get a
random number that's less than 51, or between 0 and 50. This code calls randomizer.Next(51) so that the two
random numbers add up to an answer that's between 0 and 100.
Take a closer look at these statements.

C#
VB

plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

These statements set the Text properties of plusLeftLabel and plusRightLabel so that they display the two
random numbers. Label controls display values in text format, and in programming, strings hold text. Each
integer's ToString() method converts the integer into text that a label can display.

Create random subtraction, multiplication, and division problems


The next step is to declare variables and provide random values for the other math problems.
1. Add integer variables for the remaining math problems to your form, after the addition problem
variables. The code should look like the following sample.
C#
VB
public partial class Form1 : Form
{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();

// These integer variables store the numbers


// for the addition problem.
int addend1;
int addend2;

// These integer variables store the numbers


// for the subtraction problem.
int minuend;
int subtrahend;

// These integer variables store the numbers


// for the multiplication problem.
int multiplicand;
int multiplier;

// These integer variables store the numbers


// for the division problem.
int dividend;
int divisor;

1. Modify the StartTheQuiz() method by adding the following code, starting with the "Fill in the subtraction
problem" comment.

C#
VB
/// <summary>
/// Start the quiz by filling in all of the problem
/// values and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);

// Convert the two randomly generated numbers


// into strings so that they can be displayed
// in the label controls.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

// 'sum' is the name of the NumericUpDown control.


// This step makes sure its value is zero before
// adding any values to it.
sum.Value = 0;

// Fill in the subtraction problem.


minuend = randomizer.Next(1, 101);
subtrahend = randomizer.Next(1, minuend);
minusLeftLabel.Text = minuend.ToString();
minusRightLabel.Text = subtrahend.ToString();
difference.Value = 0;

// Fill in the multiplication problem.


multiplicand = randomizer.Next(2, 11);
multiplier = randomizer.Next(2, 11);
timesLeftLabel.Text = multiplicand.ToString();
timesRightLabel.Text = multiplier.ToString();
product.Value = 0;

// Fill in the division problem.


divisor = randomizer.Next(2, 11);
int temporaryQuotient = randomizer.Next(2, 11);
dividend = divisor * temporaryQuotient;
dividedLeftLabel.Text = dividend.ToString();
dividedRightLabel.Text = divisor.ToString();
quotient.Value = 0;

This code uses the Next() method of the Random class a little differently from how the addition problem does.
When you give the Next() method two values, it picks a random number that's greater than or equal to the first
value and less than the second one.
By using the Next() method with two arguments, you can ensure the subtraction problem has a positive
answer, the multiplication answer is at most 100, and the division answer isn't a fraction.

Add an event handler to the start button


In this section, you add code to start the quiz when the start button is selected. Code that runs in reaction to an
event like a button selection is called an event handler.
1. In Windows Forms Designer , either double-click the Star t the quiz button, or select it and then select
Enter . The form's code appears, and a new method is visible.
These actions add a Click event handler to the start button. When a quiz taker selects this button, the app
runs the code that you'll add to this new method.
2. Add the following two statements so that the event handler starts the quiz.
C#
VB

private void startButton_Click(object sender, EventArgs e)


{
StartTheQuiz();
startButton.Enabled = false;
}

The first statement calls the new StartTheQuiz() method. The second statement sets the Enabled property of
the star tButton control to false so that the quiz taker can't select the button during a quiz.

Run your app


1. Save your code.
2. Run your app, and then select Star t the quiz . Random math problems appear, as the following
screenshot shows.

Next steps
Advance to the next tutorial to add a timer to your math quiz and check user answers.
Tutorial part 3: Add a timer control to a math quiz WinForms app
Tutorial: Add a Timer control to a math quiz
WinForms app
6/24/2022 • 9 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you'll build a math quiz. The quiz contains four random math problems that a quiz
taker tries to answer within a specified time.
The quiz uses a Timer control. The code behind this control tracks the elapsed time and checks the quiz taker's
answers.
In this third tutorial, you learn how to:
Add a Timer control.
Add an event handler for the timer.
Write code to check the user's answers, display messages, and fill in the correct answers.

Prerequisites
This tutorial builds on previous tutorials, starting with Create a math quiz WinForms app. If you haven't
completed those tutorials, go through them first.

Add a countdown timer


To keep track of time during the quiz, you use a timer component. You also need a variable to store the amount
of time that's left.
1. Add an integer variable that's named timeLeft in the same way that you declared variables in previous
tutorials. Put the timeLeft declaration right after the other declarations. Your code should look like the
following sample.
C#
VB
public partial class Form1 : Form
{
// Create a Random object called randomizer
// to generate random numbers.
Random randomizer = new Random();

// These integer variables store the numbers


// for the addition problem.
int addend1;
int addend2;

// These integer variables store the numbers


// for the subtraction problem.
int minuend;
int subtrahend;

// These integer variables store the numbers


// for the multiplication problem.
int multiplicand;
int multiplier;

// These integer variables store the numbers


// for the division problem.
int dividend;
int divisor;

// This integer variable keeps track of the


// remaining time.
int timeLeft;

IMPORTANT
Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic
code snippet.

1. In Windows Forms Designer , move a Timer control from the Components category of the Toolbox
to your form. The control appears in the gray area at the bottom of the design window.
2. On the form, select the timer1 icon that you just added, and set its Inter val property to 1000 . Because
this interval is in milliseconds, a value of 1000 causes the timer to raise a Tick event every second.

Check the answers


Because the timer raises a Tick event every second, it makes sense to check the elapsed time in a Tick event
handler. It's also practical to check the answers in that event handler. If time has run out, or if the answers are
correct, the quiz should end.
Before you write that event handler, add a method called CheckTheAnswer() to determine whether the answers
to the math problems are correct. This method should be in line with the other methods, such as
StartTheQuiz() . Your code should look like the following sample.
C#
VB

/// <summary>
/// Check the answers to see if the user got everything right.
/// </summary>
/// <returns>True if the answer's correct, false otherwise.</returns>
private bool CheckTheAnswer()
{
if ((addend1 + addend2 == sum.Value)
&& (minuend - subtrahend == difference.Value)
&& (multiplicand * multiplier == product.Value)
&& (dividend / divisor == quotient.Value))
return true;
else
return false;
}

This method determines the answers to the math problems and compares the results to the values in the
NumericUpDown controls. In this code:
The Visual Basic version uses the Function keyword instead of the usual Sub keyword because this
method returns a value.
You can't easily enter the multiplication sign (×) and the division sign (÷) by using the keyboard, so C#
and Visual Basic accept an asterisk (*) for multiplication and a slash mark (/) for division.
In C#, is the logical and operator. In Visual Basic, the equivalent operator is AndAlso . You use the
&&
logical and operator to check whether more than one condition is true. In this case, if the values are all
correct, the method returns a value of true . Otherwise, the method returns a value of false .
The if statement uses the Value property of a NumericUpDown control to access the control's current
value. In the next section, you use the same property to display the correct answer in each control.

Add an event handler to the timer


Now that you have a way to check the answers, you can write the code for the Tick event handler. This code runs
every second, after the timer raises a Tick event. This event handler checks the quiz taker's answers by calling
CheckTheAnswer() . It also checks how much time has elapsed in the quiz.

1. On the form, double-click the Timer control, or select it and then select Enter . These actions add a Tick
event handler to the timer. The code editor appears and displays the Tick handler's method.
2. Add the following statements to the new event handler method.

C#
VB
private void timer1_Tick(object sender, EventArgs e)
{
if (CheckTheAnswer())
{
// If CheckTheAnswer() returns true, then the user
// got the answer right. Stop the timer
// and show a MessageBox.
timer1.Stop();
MessageBox.Show("You got all the answers right!",
"Congratulations!");
startButton.Enabled = true;
}
else if (timeLeft > 0)
{
// If CheckTheAnswer() returns false, keep counting
// down. Decrease the time left by one second and
// display the new time left by updating the
// Time Left label.
timeLeft = timeLeft - 1;
timeLabel.Text = timeLeft + " seconds";
}
else
{
// If the user ran out of time, stop the timer, show
// a MessageBox, and fill in the answers.
timer1.Stop();
timeLabel.Text = "Time's up!";
MessageBox.Show("You didn't finish in time.", "Sorry!");
sum.Value = addend1 + addend2;
difference.Value = minuend - subtrahend;
product.Value = multiplicand * multiplier;
quotient.Value = dividend / divisor;
startButton.Enabled = true;
}
}

Each second of the quiz, this method runs. The code first checks the value that CheckTheAnswer() returns.
If all answers are correct, that value is true , and the quiz ends:
The timer stops.
A congratulatory message appears.
The Enabled property of the star tButton control is set to true so that the quiz taker can start
another quiz.
If CheckTheAnswer() returns false , the code checks the value of timeLeft :
If this variable is greater than 0, the timer subtracts 1 from timeLeft . It also updates the Text property
of the timeLabel control to show the quiz taker how many seconds remain.
If no time remains, the timer stops and changes the timeLabel text to Time's up! A message box
announces that the quiz is over, and the answers are revealed. The start button becomes available
again.

Start the timer


To start the timer when the quiz starts, add three lines to the end of the StartTheQuiz() method, as the
following sample shows.
C#
VB
/// <summary>
/// Start the quiz by filling in all of the problem
/// values and starting the timer.
/// </summary>
public void StartTheQuiz()
{
// Fill in the addition problem.
// Generate two random numbers to add.
// Store the values in the variables 'addend1' and 'addend2'.
addend1 = randomizer.Next(51);
addend2 = randomizer.Next(51);

// Convert the two randomly generated numbers


// into strings so that they can be displayed
// in the label controls.
plusLeftLabel.Text = addend1.ToString();
plusRightLabel.Text = addend2.ToString();

// 'sum' is the name of the NumericUpDown control.


// This step makes sure its value is zero before
// adding any values to it.
sum.Value = 0;

// Fill in the subtraction problem.


minuend = randomizer.Next(1, 101);
subtrahend = randomizer.Next(1, minuend);
minusLeftLabel.Text = minuend.ToString();
minusRightLabel.Text = subtrahend.ToString();
difference.Value = 0;

// Fill in the multiplication problem.


multiplicand = randomizer.Next(2, 11);
multiplier = randomizer.Next(2, 11);
timesLeftLabel.Text = multiplicand.ToString();
timesRightLabel.Text = multiplier.ToString();
product.Value = 0;

// Fill in the division problem.


divisor = randomizer.Next(2, 11);
int temporaryQuotient = randomizer.Next(2, 11);
dividend = divisor * temporaryQuotient;
dividedLeftLabel.Text = dividend.ToString();
dividedRightLabel.Text = divisor.ToString();
quotient.Value = 0;

// Start the timer.


timeLeft = 30;
timeLabel.Text = "30 seconds";
timer1.Start();
}

When your quiz starts, this code sets the timeLeft variable to 30 and the Text property of the timeLabel
control to 30 seconds. Then the Start() method of the Timer control starts the countdown.

Run your app


1. Save your program and run it.
2. Select Star t the quiz . The timer starts to count down. When time runs out, the quiz ends, and the
answers appear.
3. Start another quiz, and provide correct answers to the math problems. When you answer correctly within
the time limit, a message box opens, the start button becomes available, and the timer stops.
Next steps
Advance to the next tutorial to learn how to customize your math quiz.
Tutorial part 4: Customize a math quiz WinForms app
Tutorial: Customize a math quiz WinForms app
6/24/2022 • 4 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you'll build a math quiz. The quiz contains four random math problems that a quiz
taker tries to answer within a specified time.
This tutorial shows you how to enhance your quiz by clearing default values and by customizing the appearance
of controls.
In this final tutorial, you learn how to:
Add event handlers to clear the default NumericUpDown control values.
Customize the quiz.

Prerequisites
This tutorial builds on previous tutorials, starting with Create a math quiz WinForms app. If you haven't
completed those tutorials, go through them first.

Add Event handlers for the NumericUpDown controls


The quiz contains NumericUpDown controls that quiz takers use to enter numbers. When you enter an answer,
you either need to select the default value first or delete that value manually. By adding an Enter event handler,
you can make it easier to enter answers. This code selects and clears the current value in each NumericUpDown
control as soon as the quiz taker selects it and starts to enter a different value.
1. Select the first NumericUpDown control on the form. In the Proper ties dialog box, select the Events
icon on the toolbar.

The Events tab in Proper ties displays all the events that you can respond to for the item that you
selected on the form. In this case, all the listed events pertain to the NumericUpDown control.
2. Select the Enter event, enter answer_Enter , and then select Enter .

The code editor appears and displays the Enter event handler that you created for the sum
NumericUpDown control.
3. In the method for the answer_Enter event handler, add the following code:
C#
VB

private void answer_Enter(object sender, EventArgs e)


{
// Select the whole answer in the NumericUpDown control.
NumericUpDown answerBox = sender as NumericUpDown;

if (answerBox != null)
{
int lengthOfAnswer = answerBox.Value.ToString().Length;
answerBox.Select(0, lengthOfAnswer);
}
}

IMPORTANT
Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic
code snippet.

In this code:
The first line declares the method. It includes a parameter that's named sender . In C#, the parameter is
object sender . In Visual Basic, it's sender As System.Object . This parameter refers to the object whose event
is firing, which is known as the sender. In this case, the sender object is the NumericUpDown control.
The first line inside the method casts, or converts, the sender from a generic object to a NumericUpDown
control. That line also assigns the name answerBox to the NumericUpDown control. All the
NumericUpDown controls on the form will use this method, not just the addition problem's control.
The next line verifies whether answerBox was successfully cast as a NumericUpDown control.
The first line inside the if statement determines the length of the answer that's currently in the
NumericUpDown control.
The second line inside the if statement uses the answer length to select the current value in the control.
When the quiz taker selects the control, Visual Studio fires this event. This code selects the current answer. As
soon as the quiz taker starts to enter a different answer, the current answer is cleared and replaced with the new
answer.
1. In Windows Forms Designer , select the subtraction problem's NumericUpDown control.
2. In the Events page of the Proper ties dialog box, find the Enter event, and then select answer_Enter
from the drop-down menu. This event handler is the one that you just added.
3. Repeat the previous two steps for the multiplication and division NumericUpDown controls.

Run your app


1. Save your program and run it.
2. Start a quiz, and select a NumericUpDown control. The existing value is automatically selected and then
cleared when you start to enter a different value.

Customize your quiz


In this last part of the tutorial, you'll explore some ways to customize the quiz and expand on what you've
learned.
Change the color of a label
Use the BackColor property of the timeLabel control to turn this label red when only five seconds
remain in a quiz.

C#
VB

timeLabel.BackColor = Color.Red;

Reset the color when the quiz is over.


Play a sound for a correct answer
Give the quiz taker a hint by playing a sound when the correct answer is entered into a NumericUpDown
control. To implement this functionality, write an event handler for each control's ValueChanged event. This type
of event fires whenever a quiz taker changes the control's value.

Next steps
Congratulations! You've finished this series of tutorials. You've completed these programming and design tasks
in the Visual Studio IDE:
Created a Visual Studio project that uses Windows Forms
Added labels, a button, and NumericUpDown controls
Added a timer
Set up event handlers for your controls
Written C# or Visual Basic code to handle the events
Continue learning with another tutorial series on how to build a matching game.
Tutorial 3: Create a matching game
Tutorial: Create a matching game WinForms app
6/24/2022 • 5 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches pairs of hidden icons.
Use these tutorials to learn about the following tasks in the Visual Studio Integrated Design Environment (IDE).
Store objects, such as icons, in a List<T> object.
Use a foreach loop in C# or a For Each loop in Visual Basic to iterate through items in a list.
Keep track of a form's state by using reference variables.
Build an event handler to respond to events that you can use with multiple objects.
Make a timer that counts down and then fires an event exactly once after being started.
When you finish, you'll have a complete game.

In this first tutorial, you learn how to:


Create a Visual Studio project that uses Windows Forms.
Add and format a layout element.
Add and format labels to display.

Prerequisites
You need Visual Studio to complete this tutorial. Visit the Visual Studio downloads page for a free version.
Create your Windows Forms match game project
When you create your matching game, the first step is to create a Windows Forms App project.
1. Open Visual Studio.
2. On the start window, select Create a new project .

3. On the Create a new project window, search for Windows Forms. Then select Desktop from the All
project types list.
4. Select the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then
select Next .
NOTE
If you don't see the Windows Forms App (.NET Framework) template, you can install it from the Create a
new project window. In the Not finding what you're looking for? message, select the Install more tools
and features link.

Next, in Visual Studio Installer, select .NET desktop development .

Select Modify in the Visual Studio Installer. You might be prompted to save your work. Next, select Continue to
install the workload.

5. In the Configure your new project window, name your project MatchingGame, then select Create .
Visual Studio creates a solution for your app. A solution is a container for all of the projects and files needed by
your app.
At this point, Visual Studio displays an empty form in the Windows Form Designer .

Create a layout for your game


In this section, you create the four-by-four grid of the game.
1. Click on the form to select the Windows Forms Designer. The tab reads Form1.cs [Design] for C# or
Form1.vb [Design] for Visual Basic. In the Proper ties window, set the following form properties.
Change the Text property from Form1 to Matching Game . This text appears at the top of the game
window.
Set the size of the form. You can change it either by setting the Size property to 550, 550 , or by
dragging the corner of the form until you see the correct size at the bottom of the Visual Studio IDE.
2. Select the Toolbox tab on the left side of the IDE. If you don't see it, select View > Toolbox from the
menu bar or Ctrl +Alt +X .
3. Drag a TableLayoutPanel control from the Containers category in the toolbox or double-click it. Set the
following properties for the panel in the Proper ties window.
Set the BackColor property to CornflowerBlue . To do set this property, select the arrow next to
the BackColor property. In the BackColor dialog box, select Web . In the available color names,
select CornflowerBlue .

NOTE
The colors are not in alphabetical order, and CornflowerBlue is near the bottom of the list.

Set the Dock property to Fill from the dropdown list by selecting the large middle button. This
option spreads the table out so that it covers the entire form.
Set the CellBorderStyle property to Inset . This value provides visual borders between each cell
on the board.
Select the triangle button in the upper-right corner of the TableLayoutPanel to display its task
menu. On the task menu, select Add Row twice to add two more rows. Then select Add Column
twice to add two more columns.
On the task menu, select Edit Rows and Columns to open the Column and Row Styles
window. For each column, select the Percent option, and then set each column's width to 25
percent.
Select Rows from the list at the top of the window, and then set each row's height to 25 percent.
When you're done, select OK to save your changes.
Your TableLayoutPanel is now a four-by-four grid with 16 equally-sized square cells. These rows and columns
are where the icons appear later.

Add and format labels to display


In this section, you create and format labels to display during the game.
1. Be certain that the TableLayoutPanel is selected in the form editor. You should see tableLayoutPanel1 at
the top of the Proper ties window. If it isn't selected, select the TableLayoutPanel on the form, or select it
from the list at the top of the Proper ties window.
2. Open the toolbox, as before, and open the Common Controls category. Add a Label control to the
upper-left cell of the TableLayoutPanel. The label control is now selected in the IDE. Set the following
properties for it.
Set the BackColor property of the label to CornflowerBlue .
Set the AutoSize property to False .
Set the Dock property to Fill .
Set the TextAlign property to MiddleCenter by choosing the drop-down button next to the property,
and then selecting the middle button. This value ensures the icon appears in the middle of the cell.
Select the Font property. An ellipsis (...) button appears. Select the ellipsis and set the Font value to
Webdings , the Font Style to Bold , and the Size to 48 .
Set the Text property of the label to the letter c .
The upper-left cell of the TableLayoutPanel now contains a black box centered on a blue background.

NOTE
Webdings is a font of icons that ships with the Windows operating system. In your matching game, the player
matches pairs of icons. This font displays the icons to match.
Instead of c, try different letters in the Text property. An exclamation point is a spider, an uppercase N is an eye,
and a comma is a chili pepper.

3. Select your Label control and copy it to the next cell in the TableLayoutPanel. Select the Ctrl +C keys, or
on the menu bar, Edit > Copy . Then paste it by using Ctrl +V or Edit > Paste .
A copy of the first Label appears in the second cell of the TableLayoutPanel. Paste it again, and another
Label appears in the third cell. Keep pasting Label controls until all of the cells are filled.
This step completes the layout for your form.

Next steps
Advance to the next tutorial to learn how to assign a random icon to each label and add event handlers to labels.
Add icons to your Matching Game
Tutorial: Add icons to your matching game
WinForms app
6/24/2022 • 8 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches pairs of hidden icons.
In the matching game, a player selects a square to see an icon, then chooses another square. If the icons match,
they stay visible. If not, the game hides both icons. In this tutorial, you assign icons to labels randomly. You set
them to be hidden and then displayed when selected.
In this second tutorial, you learn how to:
Add a Random object and a list of icons.
Assign a random icon to each label.
Add event handlers that show icons to the labels.

Prerequisites
This tutorial builds on the previous tutorial, Create a matching game application. If you haven't done that
tutorial, go through that one first.

Add a Random object and a list of icons


In this section, you create a set of matching symbols for the game. Each symbol is added to two random cells in
the TableLayoutPanel on the form.
You use new statements to create two objects. The first is a Random object that randomly chooses cells in the
TableLayoutPanel. The second object is a List<T> object. It stores the randomly chosen symbols.
1. Open Visual Studio. Your Matching Game project appears under Open recent .
2. Select Form1.cs if you're using C#, or Form1.vb if you're using Visual Basic. Then select View > Code . As
an alternative, select the F7 key or double-click Form1 . The Visual Studio IDE displays the code module
for Form1.
3. In the existing code, add the following code.
C#
VB
public partial class Form1 : Form
{
// Use this Random object to choose random icons for the squares
Random random = new Random();

// Each of these letters is an interesting icon


// in the Webdings font,
// and each icon appears twice in this list
List<string> icons = new List<string>()
{
"!", "!", "N", "N", ",", ",", "k", "k",
"b", "b", "v", "v", "w", "w", "z", "z"
};

IMPORTANT
Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic
code snippet.

If you're using C#, be sure you put the code after the opening curly brace and just after the class declaration (
public partial class Form1 : Form ). If you're using Visual Basic, put the code right after the class declaration (
Public Class Form1 ).

You can use list objects to keep track of different types of items. A list can hold numbers, true/false values, text,
or other objects. In your matching game, the list object has 16 strings, one for each cell in the TableLayoutPanel
panel. Each string is a single letter that corresponds to the icons in the labels. These characters appear in the
Webdings font as a bus, a bike, and others.

NOTE
Lists can shrink and grow as needed, which is important in this program.

To learn more about lists, see List<T>. To see an example in C#, see A basic list example. To see an example in
Visual Basic, see Using a Simple Collection.

Assign a random icon to each label


Each time you run the program, it assigns the icons randomly to the Label controls on your form by using an
AssignIconsToSquares() method. This code uses the keyword foreach in C# or For Each in Visual Basic.

1. Add the AssignIconsToSquares() method.

C#
VB
/// <summary>
/// Assign each icon from the list of icons to a random square
/// </summary>
private void AssignIconsToSquares()
{
// The TableLayoutPanel has 16 labels,
// and the icon list has 16 icons,
// so an icon is pulled at random from the list
// and added to each label
foreach (Control control in tableLayoutPanel1.Controls)
{
Label iconLabel = control as Label;
if (iconLabel != null)
{
int randomNumber = random.Next(icons.Count);
iconLabel.Text = icons[randomNumber];
// iconLabel.ForeColor = iconLabel.BackColor;
icons.RemoveAt(randomNumber);
}
}
}

You can enter this code just below the code you added in the previous section.

NOTE
One of the lines is commented out on purpose. You add it later in this procedure.

The AssignIconsToSquares() method iterates through each label control in the TableLayoutPanel. It runs the
same statements for each of them. The statements pull a random icon from the list.
The first line converts the control variable to a label named iconLabel .
The second line is an if statement that checks to make sure the conversion worked. If the conversion does
work, the statements in the if statement run.
The first line in the if statement creates a variable named randomNumber that contains a random
number that corresponds to one of the items in the icons list. It uses the Next() method of the Random
object. The Next method returns the random number. This line also uses the Count property of the icons list
to determine the range from which to choose the random number.
The next line assigns one of the icon list items to the Text property of the label.
The next line hides the icons. The line is commented out here so you can verify the rest of the code before
proceeding.
The last line in the if statement removes from the list the icon that has been added to the form.
1. Add a call to the AssignIconsToSquares() method to the Form1 constructor. This method fills the game
board with icons. Constructors are called when you create an object.

public Form1()
{
InitializeComponent();

AssignIconsToSquares();
}

For Visual Basic, add the AssignIconsToSquares() method call to the Form1_Load method.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AssignIconsToSquares()
End Sub

For more information, see Constructors (C# programming guide) or Use constructors and destructors.
2. Save your program and run it. It should show a form with random icons assigned to each label.

TIP
If the Webdings icons don't display properly on the form, set the UseCompatibleTextRendering property of
labels on the form to True .

3. Close your program, and then run it again. Different icons are assigned to each label.

The icons are visible now because you haven't hidden them. To hide them from the player, you can set
each label's ForeColor property to the same color as its BackColor property.
4. Stop the program. Remove the comment marks for the commented line of code inside the loop.

C#
VB

iconLabel.ForeColor = iconLabel.BackColor;

If you run the program again, the icons seem to have disappeared. Only a blue background appears. The icons
are randomly assigned and are still there.
Add event handlers to labels
In this matching game, a player reveals a hidden icon, then a second one. If the icons match, they stay visible.
Otherwise, both icons are hidden again.
To get your game to work this way, add a Click event handler that changes the color of the chosen label to match
the background.
1. Open the form in the Windows Forms Designer . Select Form1.cs or Form1.vb , and then select View
> Designer .
2. Choose the first label control to select it. Then, hold the Ctrl key while you select each of the other labels.
Be sure that every label is selected.
3. In the Proper ties window, select the Events button, which is a lightening bolt. For the Click event, select
label1_Click in the box.

4. Select the Enter key. The IDE adds a Click event handler called label1 _Click() to the code. Because
you selected all the labels, the handler is hooked to each of the labels.
5. Fill in the rest of the code.

C#
VB

/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label1_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;

if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;

clickedLabel.ForeColor = Color.Black;
}
}
NOTE
If you copy and paste the label1_Click() code block rather than entering the code manually, be sure to replace the
existing label1_Click() code. Otherwise, you'll end up with a duplicate code block.

1. Select Debug > Star t Debugging to run your program. You should see an empty form with a blue
background. Choose any of the cells in the form. One of the icons should become visible. Continue
choosing different places in the form. As you choose the icons, they should appear.

Next steps
Advance to the next tutorial to learn how to change labels using a timer.
Use a timer in your Matching Game
Tutorial: Add reference variables and a timer control
to your matching game WinForms app
6/24/2022 • 9 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches pairs of hidden icons.
Your Matching Game program needs to track which Label controls the player chooses. After a player chooses
the first label, the program should show the icon. After the second label is chosen, the program should display
both icons for a brief time. Then it hides both icons.
Your program keeps track of which Label you choose first and second by using reference variables. A timer
hides the icons and controls how long to show the icons
Add label references.
Add a timer.

Prerequisites
This tutorial builds on previous tutorials, Create a matching game application and Add icons to your matching
game. Do those tutorials first.

Add label references


In this section, you'll add two reference variables to your code. They keep track of, or refer to Label objects.
1. Add label references to your form by using the following code.
C#
VB

public partial class Form1 : Form


{
// firstClicked points to the first Label control
// that the player clicks, but it will be null
// if the player hasn't clicked a label yet
Label firstClicked = null;

// secondClicked points to the second Label control


// that the player clicks
Label secondClicked = null;
IMPORTANT
Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic
code snippet.

These statements don't cause Label controls to appear on the form because there's no new keyword. When the
program starts, both firstClicked and secondClicked are set to null for C# or Nothing for Visual Basic.
1. Modify your Click event handler to use the new firstClicked reference variable. Remove the last
statement in the label1_Click() event handler method ( clickedLabel.ForeColor = Color.Black; ) and
replace it with the if statement as follows.

C#
VB

/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label1_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;

if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;

// If firstClicked is null, this is the first icon


// in the pair that the player clicked,
// so set firstClicked to the label that the player
// clicked, change its color to black, and return
if (firstClicked == null)
{
firstClicked = clickedLabel;
firstClicked.ForeColor = Color.Black;

return;
}
}
}

1. Save and run your program. Choose one of the label controls, and its icon appears. Choose the next label
control, and notice that nothing happens.
Only the first icon that's chosen turns black. The other icons are invisible.
The program is already keeping track of the first label that the player chose. The reference firstClicked isn't
null in C# or Nothing in Visual Basic. When your if statement finds that firstClicked isn't equal to null
or Nothing , it runs the statements.

Add a timer
The Matching Game uses a Timer control the app. A timer waits, and then fires an event, referred to as a tick. A
timer can start and action or repeat an action regularly.
In your program, the timer enables a player to choose two icons. If the icons don't match, it hides the two icons
again after a short period of time.
1. Select the Toolbox tab, in the Components category, double-click or drag the Timer component to your
form. The timer icon, called timer1 , appears in a space below the form.

2. Select the Timer1 icon to select the timer. In the Proper ties window, select the Proper ties button to
view properties.
3. Set the Inter val property to 750 , which is 750 milliseconds.
The Inter val property tells the timer how long to wait between ticks, when it triggers its Tick event. Your
program calls the Start() method to start the timer after the player chooses the second label.
4. Choose the timer control icon and then press Enter , or double-click the timer. The IDE adds an empty Tick
event handler. Replace the code with the following code.

C#
VB

/// <summary>
/// This timer is started when the player clicks
/// two icons that don't match,
/// so it counts three quarters of a second
/// and then turns itself off and hides both icons
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
// Stop the timer
timer1.Stop();

// Hide both icons


firstClicked.ForeColor = firstClicked.BackColor;
secondClicked.ForeColor = secondClicked.BackColor;

// Reset firstClicked and secondClicked


// so the next time a label is
// clicked, the program knows it's the first click
firstClicked = null;
secondClicked = null;
}

The Tick event handler does three things:


It makes sure the timer isn't running by calling the Stop() method.
It uses two reference variables, firstClicked and secondClicked , to make the icons of the two labels that the
player chose invisible again.
It resets the firstClicked and secondClicked reference variables to null in C# and Nothing in Visual
Basic.
1. Go to the code editor and add code to the top and bottom of the label1_Click() event handler method.
This code will check if the timer is enabled, set the secondClicked reference variable, and start the timer.
The label1_Click() event handler method now looks as follows:

C#
VB
/// <summary>
/// Every label's Click event is handled by this event handler
/// </summary>
/// <param name="sender">The label that was clicked</param>
/// <param name="e"></param>
private void label1_Click(object sender, EventArgs e)
{
// The timer is only on after two non-matching
// icons have been shown to the player,
// so ignore any clicks if the timer is running
if (timer1.Enabled == true)
return;

Label clickedLabel = sender as Label;

if (clickedLabel != null)
{
// If the clicked label is black, the player clicked
// an icon that's already been revealed --
// ignore the click
if (clickedLabel.ForeColor == Color.Black)
return;

// If firstClicked is null, this is the first icon


// in the pair that the player clicked,
// so set firstClicked to the label that the player
// clicked, change its color to black, and return
if (firstClicked == null)
{
firstClicked = clickedLabel;
firstClicked.ForeColor = Color.Black;
return;
}

// If the player gets this far, the timer isn't


// running and firstClicked isn't null,
// so this must be the second icon the player clicked
// Set its color to black
secondClicked = clickedLabel;
secondClicked.ForeColor = Color.Black;

// If the player gets this far, the player


// clicked two different icons, so start the
// timer (which will wait three quarters of
// a second, and then hide the icons)
timer1.Start();
}
}

The code at the top of the method checks whether the timer was started by checking the value of the
Enabled property. If the player chooses the first and second Label controls and the timer starts, choosing
a third label won't do anything.
The code at the bottom of the method sets the secondClicked reference variable to track the second
Label control. Then, it sets that label icon color to black to make it visible. Then, it starts the timer in one-
shot mode, so that it waits 750 milliseconds and then fires a single tick. The timer's Tick event handler
hides the two icons and resets the firstClicked and secondClicked reference variables. The form is
ready for the player to choose another pair of icons.
NOTE
If you copy and paste the label1_Click() code block rather than entering the code manually, be sure to replace the
existing label1_Click() code. Otherwise, you'll end up with a duplicate code block.

1. Save and run your program. Select a square and the icon becomes visible. Choose another square. The icon
appears briefly and then both icons disappear.
Your program now keeps track of the first and second icons that you choose. It uses the timer to pause before
making the icons disappear.

Next steps
Advance to the next tutorial to learn how to finish your Matching Game.
Show congratulations message for your Matching Game
Tutorial: Display a message in your matching game
WinForms app
6/24/2022 • 7 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this series of four tutorials, you build a matching game, where the player matches pairs of hidden icons.
In this tutorial, you revise your Matching Game to keep matched pairs visible and to display a congratulations
message when a player wins.
In this tutorial, you learn how to:
Keep pairs visible.
Verify if a player won.
Try other features.

Prerequisites
This tutorial builds on previous tutorials, Create a matching game application, Add icons to your matching game,
and Add a timer in your matching game Do those tutorials first.

Keep pairs visible


When a player matches a pair, the game should reset itself so that it no longer keeps track of any labels that use
the firstClicked and secondClicked reference variables. It should not reset the colors for the two labels that
were matched. Those labels continue to be displayed.
1. Add the following if statement to the label_Click() event handler method. Put it near the end of the
code just above the statement where you start the timer.
C#
VB
// If the player gets this far, the timer isn't
// running and firstClicked isn't null,
// so this must be the second icon the player clicked
// Set its color to black
secondClicked = clickedLabel;
secondClicked.ForeColor = Color.Black;

// If the player clicked two matching icons, keep them


// black and reset firstClicked and secondClicked
// so the player can click another icon
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
return;
}

// If the player gets this far, the player


// clicked two different icons, so start the
// timer (which will wait three quarters of
// a second, and then hide the icons)
timer1.Start();
}
}

IMPORTANT
Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic
code snippet.

The if statement checks whether the icon in the first label that the player chooses is the same as the icon in
the second label. If the icons are the same, the program runs its three statements. The first two statements reset
the firstClicked and secondClicked reference variables. They no longer keep track of any of the labels. The
third statement is a return statement, which skips the rest of the statements in the method without running
them.
1. Run the program, and then start choosing squares on the form.
If you choose a pair that doesn't match, the timer's Tick event triggers. Both icons disappear.
If you choose a matching pair, the new if statement runs. The return statement causes the method to skip the
code that starts the timer. The icons stay visible.

Verify if a player won


You've created a fun game. After a player wins, the game should end. This section adds a method to verify
whether the player won.
1. Add a CheckForWinner() method to the bottom of your code, below the timer1_Tick() event handler.

C#
VB
/// <summary>
/// Check every icon to see if it is matched, by
/// comparing its foreground color to its background color.
/// If all of the icons are matched, the player wins
/// </summary>
private void CheckForWinner()
{
// Go through all of the labels in the TableLayoutPanel,
// checking each one to see if its icon is matched
foreach (Control control in tableLayoutPanel1.Controls)
{
Label iconLabel = control as Label;

if (iconLabel != null)
{
if (iconLabel.ForeColor == iconLabel.BackColor)
return;
}
}

// If the loop didn’t return, it didn't find


// any unmatched icons
// That means the user won. Show a message and close the form
MessageBox.Show("You matched all the icons!", "Congratulations");
Close();
}

The method uses another foreach loop in C# or For Each loop in Visual Basic to go through each label in the
TableLayoutPanel. It checks each label's icon color to verify whether it matches the background. If the colors
match, the icon remains invisible, and the player hasn't matched all of the icons remaining.
In that case, the program uses a return statement to skip the rest of the method. If the loop gets through all of
the labels without executing the return statement, that means that all of the icons on the form were matched.
The program shows a MessageBox to congratulate the player on winning, and then calls the Close() method to
end the game.
Have the label's Click event handler call the new CheckForWinner() method.

C#
VB

// If the player gets this far, the timer isn't


// running and firstClicked isn't null,
// so this must be the second icon the player clicked
// Set its color to black
secondClicked = clickedLabel;
secondClicked.ForeColor = Color.Black;

// Check to see if the player won


CheckForWinner();

// If the player clicked two matching icons, keep them


// black and reset firstClicked and secondClicked
// so the player can click another icon
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
return;
}
Be sure that your program checks for a winner immediately after it shows the second icon that the player
chooses. Look for the line where you set the second chosen icon's color, and then call the CheckForWinner()
method right after that line.
1. Save and run the program. Play the game and match all of the icons. When you win, the program
displays a congratulatory message.

After you select OK , the Matching Game closes.

Try other features


Your Matching Game is complete. You can add more features to make this game more challenging and
interesting. Here are some options.
Replace the icons and colors with ones you choose.
Try looking at the label's ForeColor property.
Add a game timer that tracks how long it takes for the player to win.
You can add a label to display the elapsed time on the form. Place it above the TableLayoutPanel . Add
another timer to the form to track the time. Use code to start the timer when the player starts the game,
and stop the timer after they match the last two icons.
Add a sound when the player finds a match, another sound when the player uncovers two icons that
don't match, and a third sound when the program hides the icons again.
To play sounds, you can use the System.Media namespace. For more information, see Play sounds in
Windows Forms app (C#) or How to play audio in Visual Basic.
Make the game more difficult by making the board bigger.
You'll need to do more than just add rows and columns to the TableLayoutPanel. You also need to
consider the number of icons you create.
Make the game more challenging by hiding the first icon if the player is too slow to respond.

Next steps
Congratulations! You've completed this series of tutorials. You've done these programming and design tasks in
the Visual Studio IDE:
Stored objects, such as icons, in a list
Used a loop in C# or Visual Basic to iterate through a list
Kept track of state by using reference variables
Built an event handler to respond to events for multiple objects
Added a timer that counts down and fires an event
Advance to this article for a deep dive into Windows Forms Designer.
Tutorial: Get started with Windows Forms Designer
Tutorial: Open a project from a repo
6/24/2022 • 8 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this tutorial, you'll use Visual Studio to connect to a repository for the first time, clone it, and then open a
project from it.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

Open a project from a GitHub repo


Visual Studio makes it easy to open a project from a repo. You can do so when you start Visual Studio, or you
can do so directly from within the Visual Studio IDE.
Here's how.
Use the start window
1. Open Visual Studio.
2. On the start window, select Clone a repositor y .

3. Enter or type the repository location, and then select the Clone button.
4. You might be asked for your user sign-in information in the Git User Information dialog box. You can
either add your information or edit the default information it provides.

Select Save to add the info to your global .gitconfig file. (Or, you can select Cancel if you'd like to add the
info later.)

TIP
For more information about signing in to Visual Studio, see the Sign in to Visual Studio page. For specific
information about how to use your GitHub account to sign in, see the Work with GitHub accounts in Visual
Studio page. And if you receive a trust notification and want to know more about it, see the Configure trust
settings for files and folders page.

View files in Solution Explorer


1. Next, Visual Studio loads the solution(s) from the repository by using the Folder View in Solution
Explorer .
You can view a solution in Solution View by double-clicking its .sln file.
Or, you can select the Switch Views button, and then select Program.cs to view a solution's code.

TIP
The default view is set to Folder View. You can change it to Solution View from the Git menu. Select Settings > Source
Control > Git Global Settings > Automatically load the solution when opening a Git repositor y to do so.

Open a project locally from a previously cloned GitHub repo


1. Open Visual Studio.
2. On the start window, select Open a project or solution .
Visual Studio opens an instance of File Explorer, where you can browse to your solution or project, and
then select it to open it.
TIP
If you've opened the project or solution recently, select it from the Open recent section to quickly open it again.

Start coding!
Use the IDE
You can also use the Git menu or the Select Repositor y control in the Visual Studio IDE to interact with a
repository's folders and files.
Here's how.
To clone a repo and open a project
1. In the Visual Studio IDE, select the Git menu, and then select Clone Repositor y .

2. Follow the prompts to connect to the Git repository that includes the files you're looking for.
To open local folders and files
1. In the Visual Studio IDE, select the Git menu, select Local Repositories , and then select Open Local
Repositor y .
Alternatively, you can perform the same task from Solution Explorer . To do so, choose the Select
Repositor y control, select the ellipsis icon that's next to the Filter repositories box, and then select
Open Local Repositor y .

2. Follow the prompts to connect to the Git repository that has the files you're looking for.

Browse to an Azure DevOps repo


Here's how to browse to and clone an Azure DevOps repo by using Visual Studio.
1. Open Visual Studio.
2. On the start window, select Clone a repositor y .

3. In the Browse a repositor y section, select Azure DevOps .


4. Follow the prompts to clone an Azure DevOps repo that includes the files you're looking for, and then
open your project.

Open a project from a GitHub repo with Visual Studio 2019


How you open a project from a GitHub repo by using Visual Studio depends on which version you have.
Specifically, if you've installed version Visual Studio 2019 version 16.8 or later, there's a new, more fully
integrated Git experience in Visual Studio available to you.
But no matter which version you've installed, you can always open a project from a GitHub repo with Visual
Studio.
Visual Studio 2019 version 16.8 and later
Here's how to use Git in Visual Studio 2019 version 16.8 or later.
Clone a GitHub repo and then open a project
1. Open Visual Studio 2019.
2. On the start window, select Clone a repositor y .
3. Enter or type the repository location, and then select Clone .

4. You might be asked for your user sign-in information in the Git User Information dialog box. You can
either add your information or edit the default information it provides.
Select Save to add the info to your global .gitconfig file. (Or, you can select Cancel if you'd like to save
the info later.)

TIP
For more information about signing in to Visual Studio, see the Sign in to Visual Studio page. And for specific
information about how to use your GitHub account to sign in, see the Work with GitHub accounts in Visual Studio
page.

Next, Visual Studio automatically loads and opens the solution from the repository.

5. If your repository contains multiple solutions, Solution Explorer displays them. For a list view of the
solutions, select the Switch Views button in Solution Explorer.
Solution Explorer then gives you the option to open the root folder in Folder View or to select a solution
file to open.

To toggle the view, select the Switch Views button again.


TIP
You can also use the Git menu in the Visual Studio IDE to clone a repo and open a project.

Open a project locally from a previously cloned GitHub repo


1. Open Visual Studio 2019 version 16.8 or later.
2. On the start window, select Open a project or solution .
Visual Studio opens an instance of File Explorer, where you can browse to your solution or project, and
then select it to open it.

If you've opened the project or solution recently, select it from the Open recent section to quickly open it
again.
TIP
You can also use the Git menu in the Visual Studio IDE to open local folders and files from a repo that you've
previously cloned.

Start coding!
Visual Studio 2019 version 16.7 and earlier
Here's how to use Git in Visual Studio 2019 version 16.7 or earlier.
Clone a GitHub repo and then open a project
1. Open Visual Studio 2019 version 16.7 or earlier.
2. On the start window, select Clone or check out code .

3. Enter or type the repository location, and then select Clone .


Visual Studio opens the project from the repo.
4. If you have a solution file available, it appears in the "Solutions and Folders" fly-out menu. Select it, and
Visual Studio opens your solution.

If you do not have a solution file (specifically, an .sln file) in your repo, the fly-out menu says "No
Solutions Found." However, you can double-click any file from the folder menu to open it in the Visual
Studio code editor.
Start coding!
Browse to an Azure DevOps repo with Visual Studio 2019
What you see when you browse to and clone an Azure DevOps repository by using Visual Studio 2019 depends
on which version you have. Specifically, if you've installed version version 16.8 or later, we've changed the UI to
accommodate a new, more fully integrated Git experience in Visual Studio in Visual Studio.
But no matter which version you have installed, you can always browse to and clone an Azure DevOps repo with
Visual Studio.
Visual Studio 2019 version 16.8 and later
1. Open Visual Studio 2019 version 16.8 or later.
2. On the start window, select Clone a repositor y .

3. In the Browse a repositor y section, select Azure DevOps .


4. If you see a sign-in window, sign in to your account.
5. In the Connect to a Project dialog box, choose the repo that you want to connect to, and then select
Clone .
TIP
If you don't see a pre-populated list of repos to connect to, select Add Azure DevOps Ser ver to enter a server
URL. (Alternatively, you might see a "No servers found" prompt that includes links to add an existing Azure
DevOps Server or to create an Azure DevOps account.)

Next, Visual Studio opens Solution Explorer that shows the folders and files.
6. Select the Team Explorer tab to view the Azure DevOps actions.
Visual Studio 2019 version 16.7 and earlier
1. Open Visual Studio 2019 version 16.7 or earlier.
2. On the start window, select Clone or check out code .
3. In the Browse a repositor y section, select Azure DevOps .

If you see a sign-in window, sign in to your account.


4. In the Connect to a Project dialog box, choose the repo that you want to connect to, and then select
Clone .
NOTE
What you see in the list box depends on the Azure DevOps repositories that you have access to.

Visual Studio opens Team Explorer and a notification appears when the clone is complete.

5. To view your folders and files, select the Show Folder View link.
Visual Studio opens Solution Explorer .
6. Choose the Solutions and Folders link to search for a solution file (specifically, an .sln file) to open.

If you do not have a solution file in your repo, a 'No Solutions Found' message appears. However, you can
double-click any file from the folder menu to open it in the Visual Studio code editor.

Next steps
Feel free to dive into any of the following language-specific tutorials:
Visual Studio tutorials | C#
Visual Studio tutorials | Visual Basic
Visual Studio tutorials | C++
Visual Studio tutorials | Python
Visual Studio tutorials | JavaScript , TypeScript , and Node.js

See also
The Git experience in Visual Studio
Compare Git and Team Explorer side-by-side
Microsoft Learn: Get started with Git and GitHub in Visual Studio
Microsoft Learn: Get started with Azure DevOps
Azure DevOps Services: Get started with Azure Repos and Visual Studio
Visual Studio version control documentation
Learn to use the code editor with Visual Basic
6/24/2022 • 10 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
In this 10-minute introduction to the code editor in Visual Studio, we'll add code to a file to look at some of the
ways that Visual Studio makes writing, navigating, and understanding Visual Basic code easier.

TIP
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

This article assumes you're already familiar with Visual Basic. If you aren't, we suggest you look at a tutorial such
as Create a simple Visual Basic (VB) console app first.

TIP
To follow along with this article, make sure you have the Visual Basic settings selected for Visual Studio. For information
about selecting settings for the integrated development environment (IDE), see Select environment settings.

Create a new code file


Start by creating a new file and adding some code to it.
1. Open Visual Studio. Press Esc or click Continue without code on the start window to open the
development environment.
2. From the File menu on the menu bar, choose New File .
3. In the New File dialog box, under the General category, choose Visual Basic Class , and then choose
Open .
A new file opens in the editor with the skeleton of a Visual Basic class. (You can already notice that you
don't have to create a full Visual Studio project to gain some of the benefits that the code editor offers,
such as syntax highlighting. All you need is a code file!)
1. Open Visual Studio. Press Esc or select Continue without code on the start window to open the
development environment.
2. From the File menu on the menu bar, choose New > File .
3. In the New File dialog box, under the General category, choose Visual Basic Class , and then choose
Open .
A new file opens in the editor with the skeleton of a Visual Basic class. (You can already notice that you
don't have to create a full Visual Studio project to gain some of the benefits that the code editor offers,
such as syntax highlighting. All you need is a code file!)

Use code snippets


Visual Studio provides useful code snippets that you can use to quickly and easily generate commonly used
code blocks. Code snippets are available for different programming languages including Visual Basic, C#, and
C++. Let's add the Visual Basic Sub snippet to our file.
1. Place your cursor above the line that says End Class , and type sub .
A pop-up dialog box appears with information about the Sub keyword and how to insert the Sub code
snippet.

2. Press Tab twice to insert the code snippet.


The outline for the Sub procedure MySub() is added to the file.
The available code snippets vary for different programming languages. You can look at the available code
snippets for Visual Basic by choosing Edit > IntelliSense > Inser t Snippet (or press Ctrl +K , Ctrl +X ). For
Visual Basic, code snippets are available for the following categories:
There are snippets for determining if a file exists on the computer, writing to a text file, reading a registry value,
executing a SQL query, or creating a For Each...Next statement, and many more.
1. Place your cursor above the line that says End Class , and type sub .
A pop-up dialog box appears with information about the Sub keyword and how to insert the Sub code
snippet.

2. Press Tab twice to insert the code snippet.


The outline for the Sub procedure MySub() is added to the file.
The available code snippets vary for different programming languages. You can look at the available code
snippets for Visual Basic by opening the right-click or context menu in the code editor and choosing Snippet >
Inser t Snippet (or press Ctrl +K , Ctrl +X ). For Visual Basic, code snippets are available for the following
categories:

Comment out code


The toolbar, which is the row of buttons under the menu bar in Visual Studio, can help make you more
productive as you code. For example, you can toggle IntelliSense completion mode, increase or decrease a line
indent, or comment out code that you don't want to compile. (IntelliSense is a coding aid that displays a list of
matching methods, amongst other things.) In this section, we'll comment out some code.

1. Paste the following code into the MySub() procedure body.


' _words is a string array that we'll sort alphabetically
Dim _words = New String() {
"the",
"quick",
"brown",
"fox",
"jumps"
}

Dim morewords = New String() {


"over",
"the",
"lazy",
"dog"
}

Dim query = From word In _words


Order By word.Length
Select word

2. We're not using the morewords array, but we may use it later so we don't want to completely delete it.
Instead, let's comment out those lines. Select the entire definition of morewords to the closing curly brace,
and then choose the Comment out the selected lines button on the toolbar. If you prefer to use the
keyboard, press Ctrl +K , Ctrl +C .

The Visual Basic comment character ' is added to the beginning of each selected line to comment out
the code.

1. Paste the following code into the MySub() procedure body.

' _words is a string array that we'll sort alphabetically


Dim _words = New String() {
"the",
"quick",
"brown",
"fox",
"jumps"
}

Dim morewords = New String() {


"over",
"the",
"lazy",
"dog"
}

Dim query = From word In _words


Order By word.Length
Select word

2. We're not using the morewords array, but we may use it later so we don't want to completely delete it.
Instead, let's comment out those lines. Select the entire definition of morewords to the closing curly brace,
and then choose the Comment out the selected lines button on the toolbar. If you prefer to use the
keyboard, press Ctrl +K , Ctrl +C .
The Visual Basic comment character ' is added to the beginning of each selected line to comment out
the code.

Collapse code blocks


You can collapse sections of code to focus just on the parts that are of interest to you. To practice, let's collapse
the _words array to one line of code. Choose the small gray box with the minus sign inside it in the margin of
the line that says Dim _words = New String() { . Or, if you're a keyboard user, place the cursor anywhere in the
array definition and press Ctrl +M , Ctrl +M .

The code block collapses to just the first line, followed by an ellipsis ( ... ). To expand the code block again, click
the same gray box that now has a plus sign in it, or press Ctrl +M , Ctrl +M again. This feature is called Outlining
and is especially useful when you're collapsing long methods or entire classes.
You can collapse sections of code to focus just on the parts that are of interest to you. To practice, let's collapse
the _words array to one line of code. Choose the small gray box with the minus sign inside it in the margin of
the line that says Dim _words = New String() { . Or, if you're a keyboard user, place the cursor anywhere in the
array definition and press Ctrl +M , Ctrl +M .

The code block collapses to just the first line, followed by an ellipsis ( ... ). To expand the code block again,
choose the same gray box that now has a plus sign in it, or press Ctrl +M , Ctrl +M again. This feature is called
Outlining and is especially useful when you're collapsing long methods or entire classes.

View symbol definitions


The Visual Studio editor makes it easy to inspect the definition of a type, method, etc. One way is to navigate to
the file that contains the definition, for example by choosing Go to Definition anywhere the symbol is
referenced. An even quicker way that doesn't move your focus away from the file you're working in is to use
Peek Definition. Let's peek at the definition of the String type.
1. Right-click on the word String and choose Peek Definition from the content menu. Or, press Alt +F12 .
A pop-up window appears with the definition of the String class. You can scroll within the pop-up
window, or even peek at the definition of another type from the peeked code.
2. Close the peeked definition window by choosing the small box with an "x" at the top right of the pop-up
window.
The Visual Studio editor makes it easy to inspect the definition of a type or class member. One way is to navigate
to the file that contains the definition, for example by choosing Go to Definition anywhere the symbol is
referenced. An even quicker way that doesn't move your focus away from the file you're working in is to use
Peek Definition. Let's peek at the definition of the String type.
1. Right-click on the word String and choose Peek Definition from the content menu. Or, press Alt +F12 .
A pop-up window appears with the definition of the String class. You can scroll within the pop-up
window, or even peek at the definition of another type from the peeked code.

2. Close the peek definition window by choosing the small box with an "x" at the top right of the pop-up
window.

Use IntelliSense to complete words


IntelliSense is an invaluable resource when you're coding. It can show you information about available members
of a type, or parameter details for different overloads of a method. You can also use IntelliSense to complete a
word after you type enough characters to disambiguate it. Let's add a line of code to print out the ordered
strings to the console window, which is the standard place for output from the program to go.
1. Below the query variable, start typing the following code:

For Each str In qu

You see IntelliSense show you Quick Info about the query symbol.

2. To insert the rest of the word query by using IntelliSense's word completion functionality, press Tab .
3. Finish off the code block to look like the following code.
For Each str In query
Console.WriteLine(str)
Next

IntelliSense is an invaluable resource when you're coding. It can show you information about available members
of a type, or parameter details for different overloads of a method. You can also use IntelliSense to complete a
word after you type enough characters to disambiguate it. Let's add a line of code to print out the ordered
strings to the console window, which is the standard place for output from the program to go.
1. Below the query variable, start typing the following code:

For Each str In qu

You see IntelliSense show you Quick Info about the query symbol.

2. To insert the rest of the word query by using IntelliSense's word completion functionality, press Tab .
3. Finish off the code block to look like the following code.

For Each str In query


Console.WriteLine(str)
Next

Refactor a name
Nobody gets code right the first time, and one of the things you might have to change is the name of a variable
or method. Let's try out Visual Studio's refactor functionality to rename the _words variable to words .
1. Place your cursor over the definition of the _words variable and choose Rename from the right-click or
context menu.
A pop-up Rename dialog box appears at the top right of the editor.
2. With the variable _words still selected, type in the desired name of words . Notice that the reference to
words in the query is also automatically renamed. Before you press Enter or click Apply , select the
Include comments checkbox in the Rename pop-up box.

3. Press Enter or click Apply .


Both occurrences of words are renamed, as well as the reference to words in the code comment.

Nobody gets code right the first time, and one of the things you might have to change is the name of a variable
or method. Let's try out Visual Studio's refactor functionality to rename the _words variable to words .
1. Place your cursor over the definition of the _words variable and choose Rename from the right-click or
context menu.
A pop-up Rename dialog box appears at the top right of the editor.
2. With the variable _words still selected, type in the desired name of words . Notice that the reference to
words in the query is also automatically renamed. Before you press Enter or Apply , select the Include
comments checkbox in the Rename pop-up box.

3. Press Enter or choose Apply .


Both occurrences of words are renamed, as well as the reference to words in the code comment.

Next steps
Learn about projects and solutions

See also
Code snippets
Navigate code
Outlining
Go To Definition and Peek Definition
Refactoring
Use IntelliSense
Compile and build in Visual Studio
6/24/2022 • 2 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
For a first introduction to building within the IDE, see Walkthrough: Building an application.
You can use any of the following methods to build an application: the Visual Studio IDE, the MSBuild command-
line tools, and Azure Pipelines:

B UIL D M ET H O D B EN EF IT S

IDE - Create builds immediately and test them in a debugger.


- Run multi-processor builds for C++ and C# projects.
- Customize different aspects of the build system.

CMake - Build projects using the CMake tool


- Use the same build system across Linux and Windows
platforms.

MSBuild command line - Build projects without installing Visual Studio.


- Run multi-processor builds for all project types.
- Customize most areas of the build system.

Azure Pipelines - Automate your build process as part of a continuous


integration/continuous delivery pipeline.
- Apply automated tests with every build.
- Employ virtually unlimited cloud-based resources for build
processes.
- Modify the build workflow and create build activities to
perform deeply customized tasks.

The documentation in this section goes into further details of the IDE-based build process. For more information
on the other methods, see CMake, MSBuild and Azure Pipelines, respectively.

NOTE
This topic applies to Visual Studio on Windows. For Visual Studio for Mac, see Compile and build in Visual Studio for Mac.

Overview of building from the IDE


When you create a project, Visual Studio created default build configurations for the project and the solution
that contains the project. These configurations define how the solutions and projects are built and deployed.
Project configurations in particular are unique for a target platform (such as Windows or Linux) and build type
(such as debug or release). You can edit these configurations however you like, and can also create your own
configurations as needed.
For a first introduction to building within the IDE, see Walkthrough: Building an application.
Next, see Building and cleaning projects and solutions in Visual Studio to learn about the different
customizations you can make to the process. Customizations include changing output directories, specifying
custom build events, managing project dependencies, managing build log files, and suppressing compiler
warnings.
From there, you can explore a variety of other tasks:
Understand build configurations
Understand build platforms
Manage project and solution properties.
Specify build events in C# and Visual Basic.
Set build options
Build multiple projects in parallel.

See also
Building (compiling) website projects
Compile and build (Visual Studio for Mac)
CMake projects in Visual Studio
Tutorial: Learn to debug Visual Basic code using
Visual Studio
6/24/2022 • 19 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
This article introduces the features of the Visual Studio debugger in a step-by-step walkthrough. If you want a
higher-level view of the debugger features, see First look at the debugger. When you debug your app, it usually
means that you are running your application with the debugger attached. When you do this, the debugger
provides many ways to see what your code is doing while it runs. You can step through your code and look at
the values stored in variables, you can set watches on variables to see when values change, you can examine the
execution path of your code, see whether a branch of code is running, and so on. If this is the first time that
you've tried to debug code, you may want to read Debugging for absolute beginners before going through this
article.
Although the demo app is Visual Basic, most of the features are applicable to C#, C++, F#, Python, JavaScript,
and other languages supported by Visual Studio (F# does not support Edit-and-continue. F# and JavaScript do
not support the Autos window). The screenshots are in Visual Basic.
In this tutorial, you will:
Start the debugger and hit breakpoints.
Learn commands to step through code in the debugger
Inspect variables in data tips and debugger windows
Examine the call stack

Prerequisites
You must have Visual Studio 2019 installed and the .NET Core cross-platform development workload.
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you need to install the workload but already have Visual Studio, go to Tools > Get Tools and Features...,
which opens the Visual Studio Installer. The Visual Studio Installer launches. Choose the .NET Core cross-
platform development workload, then choose Modify .
If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
If you need to install the workload but already have Visual Studio, go to Tools > Get Tools and Features...,
which opens the Visual Studio Installer. The Visual Studio Installer launches. Choose the .NET desktop
development workload, then choose Modify .

Create a project
First, you'll create a .NET Core console application project. The project type comes with all the template files
you'll need, before you've even added anything!
1. Open Visual Studio.
If the start window is not open, choose File > Star t Window .
2. On the start window, choose Create a new project .
3. On the Create a new project window, enter, or type console in the search box. Next, choose Visual
Basic from the Language list, and then choose Windows from the Platform list.
After you apply the language and platform filters, choose the Console App template for .NET Core, and
then choose Next .

NOTE
If you do not see the Console App template, you can install it from the Create a new project window. In the
Not finding what you're looking for? message, choose the Install more tools and features link. Then, in
the Visual Studio Installer, choose the .NET Core cross-platform development workload.

4. In the Configure your new project window, type or enter get-started-debugging in the Project name
box. Then, choose Next .
5. Choose either the recommended target framework (.NET Core 3.1) or .NET 5, and then choose Create .
Visual Studio opens your new project.
1. Open Visual Studio.
If the start window is not open, choose File > Star t Window .
2. On the start window, choose Create a new project .
3. On the Create a new project window, enter, or type console in the search box. Next, choose Visual
Basic from the Language list, and then choose Windows from the Platform list.
After you apply the language and platform filters, choose the Console Application template for .NET
Core, and then choose Next .
NOTE
If you do not see the Console Application template, you can install it from the Create a new project window.
In the Not finding what you're looking for? message, choose the Install more tools and features link.
Then, in the Visual Studio Installer, choose the .NET desktop development workload.

4. In the Configure your new project window, type or enter get-started-debugging in the Project name
box. Then, choose Next .
5. On the Additional Information window, ensure the recommended target framework is (.NET 6.0), and
then choose Create .
Visual Studio opens your new project.

Create the application


1. In Program.vb, replace all of the default code with the following code instead:
Imports System

Class ArrayExample
Public Shared Sub Main()
Dim letters As Char() = {"f"c, "r"c, "e"c, "d"c, " "c, "s"c, "m"c, "i"c, "t"c, "h"c}
Dim name As String = ""
Dim a As Integer() = New Integer(9) {}

For i As Integer = 0 To letters.Length - 1


name += letters(i)
a(i) = i + 1
SendMessage(name, a(i))
Next

Console.ReadKey()
End Sub

Private Shared Sub SendMessage(ByVal name As String, ByVal msg As Integer)


Console.WriteLine("Hello, " & name & "! Count to " & msg)
End Sub
End Class

Start the debugger!


1. Press F5 (Debug > Star t Debugging ) or the Star t Debugging button in the Debug Toolbar.
F5 starts the app with the debugger attached to the app process, but right now we haven't done anything
special to examine the code. So the app just loads and you see the console output.

Hello, f! Count to 1
Hello, fr! Count to 2
Hello, fre! Count to 3
Hello, fred! Count to 4
Hello, fred ! Count to 5
Hello, fred s! Count to 6
Hello, fred sm! Count to 7
Hello, fred smi! Count to 8
Hello, fred smit! Count to 9
Hello, fred smith! Count to 10

In this tutorial, we'll take a closer look at this app using the debugger and get a look at the debugger
features.
2. Stop the debugger by pressing the red stop button (Shift + F5 ).
3. In the console window, press a key to close the console window.
1. Press F5 (Debug > Star t Debugging ) or select the green Star t Debugging button in the Debug
Toolbar.

F5 starts the app with the debugger attached to the app process, but right now we haven't done anything
special to examine the code. So the app just loads and you see the console output.
Hello, f! Count to 1
Hello, fr! Count to 2
Hello, fre! Count to 3
Hello, fred! Count to 4
Hello, fred ! Count to 5
Hello, fred s! Count to 6
Hello, fred sm! Count to 7
Hello, fred smi! Count to 8
Hello, fred smit! Count to 9
Hello, fred smith! Count to 10

In this tutorial, we'll take a closer look at this app using the debugger and get a look at the debugger
features.
2. Stop the debugger by pressing (Shift + F5 ) or select the red Stop Debugging button in the Debug
Toolbar.

3. In the console window, press a key to close the console window.

Set a breakpoint and start the debugger


1. In the For loop of the Main function, set a breakpoint by clicking the left margin of the following line of
code:
name += letters(i)

A red circle appears where you set the breakpoint.


Breakpoints are one of the most basic and essential features of reliable debugging. A breakpoint indicates
where Visual Studio should suspend your running code so you can take a look at the values of variables,
or the behavior of memory, or whether or not a branch of code is getting run.
2. Press F5 or the Star t Debugging button , the app starts, and the debugger runs to the line of code
where you set the breakpoint.

The yellow arrow represents the statement on which the debugger paused, which also suspends app
execution at the same point (this statement has not yet executed).
If the app is not yet running, F5 starts the debugger and stops at the first breakpoint. Otherwise, F5
continues running the app to the next breakpoint.
Breakpoints are a useful feature when you know the line of code or the section of code that you want to
examine in detail. For information on the different types of breakpoints you can set, such as conditional
breakpoints, see Using breakpoints.
1. In the For loop of the Main function, set a breakpoint by clicking the left margin of the following line of
code:
name += letters(i)

A red circle appears where you set the breakpoint.


Breakpoints are one of the most basic and essential features of reliable debugging. A breakpoint indicates
where Visual Studio should suspend your running code so you can take a look at the values of variables,
or the behavior of memory, or whether or not a branch of code is getting run.
2. Press F5 (Debug > Star t Debugging ) or the Star t Debugging button in the Debug Toolbar, the app
starts, and the debugger runs to the line of code where you set the breakpoint.

The yellow arrow represents the statement on which the debugger paused, which also suspends app
execution at the same point (this statement has not yet executed).
If the app is not yet running, F5 starts the debugger and stops at the first breakpoint. Otherwise, F5
continues running the app to the next breakpoint.
Breakpoints are a useful feature when you know the line of code or the section of code that you want to
examine in detail. For information on the different types of breakpoints you can set, such as conditional
breakpoints, see Using breakpoints.

Navigate code in the debugger using step commands


Mostly, we use the keyboard shortcuts here, because it's a good way to get fast at executing your app in the
debugger (equivalent commands such as menu commands are shown in parentheses).
1. While paused in the For loop in the Main method, press F11 (or choose Debug > Step Into ) twice to
advance to the SendMessage method call.
After pressing F11 twice, you should be at this line of code:
SendMessage(name, a(i))

2. Press F11 one more time to step into the SendMessage method.
The yellow pointer advances into the SendMessage method.
F11 is the Step Into command and advances the app execution one statement at a time. F11 is a good
way to examine the execution flow in the most detail. (To move faster through code, we show you some
other options also.) By default, the debugger skips over non-user code (if you want more details, see Just
My Code).
Let's say that you are done examining the SendMessage method, and you want to get out of the method
but stay in the debugger. You can do this using the Step Out command.
3. Press Shift + F11 (or Debug > Step Out ).
This command resumes app execution (and advances the debugger) until the current method or function
returns.
You should be back in the For loop in the Main method, paused at the SendMessage method call.
4. Press F11 several times until you get back to the SendMessage method call again.
5. While paused at the method call, press F10 (or choose Debug > Step Over ) once.

Notice this time that the debugger does not step into the SendMessage method. F10 advances the
debugger without stepping into functions or methods in your app code (the code still executes). By
pressing F10 on the SendMessage method call (instead of F11 ), we skipped over the implementation
code for SendMessage (which maybe we're not interested in right now). For more information on different
ways to move through your code, see Navigate code in the debugger.
In this article, we use the keyboard shortcuts, because it's a good way to get fast at executing your app in the
debugger (equivalent commands such as menu commands are shown in parentheses).
1. While paused in the For loop in the Main method, press F11 (or choose Debug > Step Into ) twice to
advance to the SendMessage method call.
After pressing F11 twice, you should be at this line of code:
SendMessage(name, a(i))

2. Press F11 one more time to step into the SendMessage method.
The yellow pointer advances into the SendMessage method.
F11 is the Step Into command and advances the app execution one statement at a time. F11 is a good
way to examine the execution flow in the most detail. (To move faster through code, we show you some
other options also.) By default, the debugger skips over non-user code (if you want more details, see Just
My Code).
Let's say that you are done examining the SendMessage method, and you want to get out of the method
but stay in the debugger. You can do this using the Step Out command.
3. Press Shift + F11 (or Debug > Step Out ).
This command resumes app execution (and advances the debugger) until the current method or function
returns.
You should be back in the For loop in the Main method, paused at the SendMessage method call.
4. Press F11 several times until you get back to the SendMessage method call again.
5. While paused at the method call, press F10 (or choose Debug > Step Over ) once.

Notice this time that the debugger does not step into the SendMessage method. F10 advances the
debugger without stepping into functions or methods in your app code (the code still executes). By
pressing F10 on the SendMessage method call (instead of F11 ), we skipped over the implementation
code for SendMessage (which maybe we're not interested in right now). For more information on different
ways to move through your code, see Navigate code in the debugger.

Navigate code using Run to Click


1. Press F5 to advance to the breakpoint again.
2. In the code editor, scroll down and hover over the Console.WriteLine method in the SendMessage method
until the green Run to Click button appears on the left. The tooltip for the button shows "Run
execution to here".

NOTE
The Run to Click button is new in Visual Studio 2017. (If you don't see the green arrow button, use F11 in this
example instead to advance the debugger to the right place.)

3. Click the Run to Click button .


The debugger advances to the Console.WriteLine method.
Using this button is similar to setting a temporary breakpoint. Run to Click is handy for getting around
quickly within a visible region of app code (you can click in any open file).
1. Press F5 to advance to the breakpoint again.
2. In the code editor, scroll down and hover over the Console.WriteLine method in the SendMessage method
until the green Run to Click button appears on the left. The tooltip for the button shows "Run execution
to here".

3. Select the Run to Click button.


The debugger advances to the Console.WriteLine method.
Using this button is similar to setting a temporary breakpoint. Run to Click is handy for getting around
quickly within a visible region of app code (you can click in any open file).

Restart your app quickly


Click the Restar t button in the Debug Toolbar (Ctrl + Shift + F5 ).
When you press Restar t , it saves time versus stopping the app and restarting the debugger. The debugger
pauses at the first breakpoint that is hit by executing code.
The debugger stops again at the breakpoint you previously set inside the For loop.
To restart your app, press the Ctrl + Shift + F5 key combination, it saves time versus stopping the app and
restarting the debugger. The debugger pauses at the first breakpoint that is hit by executing code.
The debugger stops again at the breakpoint you previously set inside the For loop.

Inspect variables with data tips


Features that allow you to inspect variables are one of the most useful features of the debugger, and there are
different ways to do it. Often, when you try to debug an issue, you are attempting to find out whether variables
are storing the values that you expect them to have at a particular time.
1. While paused on the name += letters[i] statement, hover over the letters variable and you see its
default value, the value of the first element in the array, "f"c .
2. Next, hover over the name variable, and you see its current value, an empty string.
3. Press F5 (or Debug > Continue ) a few times to iterate several times through the For loop, pausing
again at the breakpoint, and hovering over the name variable each time to check its value.

The value of the variable changes with each iteration of the For loop, showing values of f , then fr ,
then fre , and so on.
Often, when debugging, you want a quick way to check property values on variables, to see whether they
are storing the values that you expect them to store, and the data tips are a good way to do it.
Features that allow you to inspect variables are one of the most useful features of the debugger, and there are
different ways to do it. Often, when you try to debug an issue, you are attempting to find out whether variables
are storing the values that you expect them to have at a particular time.
1. While paused on the name += letters[i] statement, hover over the letters variable and you see its
default value, the value of the first element in the array, "f"c .
2. Next, hover over the name variable, and you see its current value, an empty string.
3. Press F5 (or Debug > Continue ) a few times to iterate several times through the For loop, pausing
again at the breakpoint, and hovering over the name variable each time to check its value.

The value of the variable changes with each iteration of the For loop, showing values of f , then fr ,
then fre , and so on.
Often, when debugging, you want a quick way to check property values on variables, to see whether they
are storing the values that you expect them to store, and the data tips are a good way to do it.

Inspect variables with the Autos and Locals windows


1. Look at the Autos window at the bottom of the code editor.
If it is closed, open it while paused in the debugger by choosing Debug > Windows > Autos .
In the Autos window, you see variables and their current value. The Autos window shows all variables
used on the current line or the preceding line (Check documentation for language-specific behavior).
2. Next, look at the Locals window, in a tab next to the Autos window.
3. Expand the letters variable to show the elements that it contains.

The Locals window shows you the variables that are in the current scope, that is, the current execution
context.
1. Look at the Autos window at the bottom of the code editor.
If it is closed, open it while paused in the debugger by choosing Debug > Windows > Autos .
In the Autos window, you see variables and their current value. The Autos window shows all variables
used on the current line or the preceding line (Check documentation for language-specific behavior).
2. Next, look at the Locals window, in a tab next to the Autos window.
3. Expand the letters variable to show the elements that it contains.

The Locals window shows you the variables that are in the current scope, that is, the current execution
context.

Set a watch
1. In the main code editor window, right-click the name variable and choose Add Watch .
The Watch window opens at the bottom of the code editor. You can use a Watch window to specify a
variable (or an expression) that you want to keep an eye on.
Now, you have a watch set on the name variable, and you can see its value change as you move through
the debugger. Unlike the other variable windows, the Watch window always shows the variables that you
are watching (they're grayed out when out of scope).

Examine the call stack


1. While paused in the For loop, click the Call Stack window, which is by default open in the lower right
pane.
If it is closed, open it while paused in the debugger by choosing Debug > Windows > Call Stack .
2. Click F11 a few times until you see the debugger pause in the SendMessage method. Look at the Call
Stack window.
The Call Stack window shows the order in which methods and functions are getting called. The top line
shows the current function (the SendMessage method in this app). The second line shows that
SendMessage was called from the Main method, and so on.

NOTE
The Call Stack window is similar to the Debug perspective in some IDEs like Eclipse.

The call stack is a good way to examine and understand the execution flow of an app.
You can double-click a line of code to go look at that source code and that also changes the current scope
being inspected by the debugger. This action does not advance the debugger.
You can also use right-click menus from the Call Stack window to do other things. For example, you can
insert breakpoints into specified functions, advance the debugger using Run to Cursor , and go examine
source code. For more information, see How to: Examine the Call Stack.
1. While paused in the For loop, click the Call Stack window, which is open by default in the lower right
pane.
If it is closed, open it while paused in the debugger by choosing Debug > Windows > Call Stack .
2. Click F11 a few times until you see the debugger pause in the SendMessage method. Look at the Call
Stack window.

The Call Stack window shows the order in which methods and functions are getting called. The top line
shows the current function (the SendMessage method in this app). The second line shows that
SendMessage was called from the Main method, and so on.

NOTE
The Call Stack window is similar to the Debug perspective in some IDEs like Eclipse.

The call stack is a good way to examine and understand the execution flow of an app.
You can double-click a line of code to go look at that source code and that also changes the current scope
being inspected by the debugger. This action does not advance the debugger.
You can also use right-click menus from the Call Stack window to do other things. For example, you can
insert breakpoints into specified functions, advance the debugger using Run to Cursor , and go examine
source code. For more information, see How to: Examine the Call Stack.

Change the execution flow


1. Press F11 twice to run the Console.WriteLine method.
2. With the debugger paused in the SendMessage method call, use the mouse to grab the yellow arrow (the
execution pointer) on the left and move it up one line, back to Console.WriteLine .
3. Press F11 .
The debugger reruns the Console.WriteLine method (you see this in the console window output).
By changing the execution flow, you can do things like test different code execution paths or rerun code
without restarting the debugger.

WARNING
Often you need to be careful with this feature, and you see a warning in the tooltip. You may see other warnings,
too. Moving the pointer cannot revert your application to an earlier app state.

4. Press F5 to continue running the app.


Congratulations on completing this tutorial!

Next steps
In this tutorial, you've learned how to start the debugger, step through code, and inspect variables. You may
want to get a high-level look at debugger features along with links to more information.
First look at the debugger
Get started with unit testing
6/24/2022 • 6 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
Use Visual Studio to define and run unit tests to maintain code health, ensure code coverage, and find errors and
faults before your customers do. Run your unit tests frequently to make sure your code is working properly.
In this article, the code uses C# and C++, illustrations are in C#, but the concepts and features apply to .NET
languages, C++, Python, JavaScript, and TypeScript.

Create unit tests


This section describes how to create a unit test project.
1. Open the project that you want to test in Visual Studio.
For the purposes of demonstrating an example unit test, this article tests a simple "Hello World" C# or
C++ Console project named HelloWorld . The sample code for such a project is as follows:
.NET
C++

namespace HelloWorld
{
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World!");
}
}
}

2. In Solution Explorer , select the solution node. Then, from the top menu bar, select File > Add > New
Project .
3. In the new project dialog box, find the unit test project to use.
Type test in the search box to find a unit test project template for the test framework you want to use,
such as MSTest (C#) or the Native Unit Test project (C++), and select it.
Starting in Visual Studio 2017 version 14.8, the .NET languages include built-in templates for NUnit and
xUnit. For C++, in this example select the Native Unit Test project, which uses Microsoft Native Unit Test
Framework. (To use a different C++ test framework, see Writing unit tests for C/C++). For Python, see
Set up unit testing in Python code to set up your test project.

TIP
For C# only, you can create unit test projects from code using a faster method. For more information, see Create
unit test projects and test methods. To use this method with .NET Core or .NET Standard, Visual Studio 2019 or
later is required.
The following illustration shows an MSTest unit test, which is supported in .NET.

Click Next , choose a name for the test project, and then click Create .

Click Next , choose a name for the test project, and then click Create .
The project is added to your solution.
4. In the unit test project, add a reference to the project you want to test by right-clicking on References or
Dependencies and then choosing Add Reference or Add Project Reference .
5. Select the project that contains the code you'll test and click OK .
6. Add code to the unit test method.
For example, you might use the following code by selecting the correct documentation tab that matches
your test framework: MSTest, NUnit, or xUnit (supported on .NET only), or C++ Microsoft Native Unit Test
Framework.
MSTest
NUnit
xUnit
Microsoft Native Unit Test Framework

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System;

namespace HelloWorldTests
{
[TestClass]
public class UnitTest1
{
private const string Expected = "Hello World!";
[TestMethod]
public void TestMethod1()
{
using (var sw = new StringWriter())
{
Console.SetOut(sw);
HelloWorld.Program.Main();

var result = sw.ToString().Trim();


Assert.AreEqual(Expected, result);
}
}
}
}

Run unit tests


1. Open Test Explorer.
To open Test Explorer, choose Test > Test Explorer from the top menu bar (or press Ctrl + E , T ).
2. Run your unit tests by clicking Run All (or press Ctrl + R , V ).
After the tests have completed, a green check mark indicates that a test passed. A red "x" icon indicates
that a test failed.
TIP
You can use Test Explorer to run unit tests from the built-in test framework (MSTest) or from third-party test frameworks.
You can group tests into categories, filter the test list, and create, save, and run playlists of tests. You can also debug tests
and analyze test performance and code coverage.

View live unit test results (Visual Studio Enterprise)


If you are using the MSTest, xUnit, or NUnit testing framework in Visual Studio 2017 or later, you can see live
results of your unit tests.

NOTE
To follow these steps, Visual Studio Enterprise is required, along with .NET code and one of the following test frameworks:
MSTest, xUnit, or NUnit.

1. Turn live unit testing from the Test menu by choosing Test > Live Unit Testing > Star t .
2. View the results of the tests within the code editor window as you write and edit code.

3. Click a test result indicator to see more information, such as the names of the tests that cover that
method.
For more information about live unit testing, see Live unit testing.

Use a third-party test framework


You can run unit tests in Visual Studio by using third-party test frameworks such as NUnit, Boost, or Google
C++ Testing Framework, depending on your programming language. To use a third-party framework:
Use the NuGet Package Manager to install the NuGet package for the framework of your choice.
(.NET) Starting in Visual Studio 2017 version 14.6, Visual Studio includes pre-configured test project
templates for NUnit and xUnit test frameworks. The templates also include the necessary NuGet
packages to enable support.
(C++) In Visual Studio 2017 and later versions, some frameworks like Google C++ Testing Framework
are already included. For more information, see Write unit tests for C/C++ in Visual Studio.
To add a unit test project:
1. Open the solution that contains the code you want to test.
2. Right-click on the solution in Solution Explorer and choose Add > New Project .
3. Select a unit test project template.
In this example, select NUnit
Click Next , name the project, and then click Create .
The project template includes NuGet references to NUnit and NUnit3TestAdapter.
4. Add a reference from the test project to the project that contains the code you want to test.
Right-click on the project in Solution Explorer , and then select Add > Reference . (You can also add a
reference from the right-click menu of the References or Dependencies node.)
5. Add code to your test method.
6. Run the test from Test Explorer or by right-clicking on the test code and choosing Run Test(s) (or Ctrl
+ R , T ).

Next steps
Unit test basics
Create and run unit tests for managed code
Write unit tests for C/C++
Create a database and add tables in Visual Studio
6/24/2022 • 6 minutes to read • Edit Online

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code
You can use Visual Studio to create and update a local database file in SQL Server Express LocalDB. You can also
create a database by executing Transact-SQL statements in the SQL Ser ver Object Explorer tool window in
Visual Studio. In this topic, we'll create an .mdf file and add tables and keys by using the Table Designer.

Prerequisites
To complete this walkthrough, you'll need the .NET desktop development and Data storage and
processing workloads installed in Visual Studio. To install them, open Visual Studio Installer and choose
Modify (or More > Modify ) next to the version of Visual Studio you want to modify.

NOTE
The procedures in this article apply only to .NET Framework Windows Forms projects, not to .NET Core Windows Forms
projects.

Create a project and a local database file


1. Create a new Windows Forms App (.NET Framework) project and name it
SampleDatabaseWalkthrough .
2. On the menu bar, select Project > Add New Item .
3. In the list of item templates, scroll down and select Ser vice-based Database .
4. Name the database SampleDatabase , and then click Add .
Add a data source
1. If the Data Sources window isn't open, open it by pressing Shift +Alt +D or selecting View > Other
Windows > Data Sources on the menu bar.
2. In the Data Sources window, select Add New Data Source .

The Data Source Configuration Wizard opens.


3. On the Choose a Data Source Type page, choose Database and then choose Next .
4. On the Choose a Database Model page, choose Next to accept the default (Dataset).
5. On the Choose Your Data Connection page, select the SampleDatabase.mdf file in the drop-down
list, and then choose Next .
6. On the Save the Connection String to the Application Configuration File page, choose Next .
7. On the Choose your Database Objects page, you'll see a message that says the database doesn't
contain any objects. Choose Finish .
View properties of the data connection
You can view the connection string for the SampleDatabase.mdf file by opening the Properties window of the
data connection:
Select View > SQL Ser ver Object Explorer to open the SQL Ser ver Object Explorer window.
Expand (localdb)\MSSQLLocalDB > Databases , and then right-click on SampleDatabase.mdf and
select Proper ties .
Alternatively, you can select View > Ser ver Explorer , if that window isn't already open. Open the
Properties window by expanding the Data Connections node, right-clicking on SampleDatabase.mdf,
and then selecting Proper ties .

TIP
If you can't expand the Data Connections node, or the SampleDatabase.mdf connection is not listed, select the
Connect to Database button in the Server Explorer toolbar. In the Add Connection dialog box, make sure
that Microsoft SQL Ser ver Database File is selected under Data source , and then browse to and select the
SampleDatabase.mdf file. Finish adding the connection by selecting OK .

Create tables and keys by using Table Designer


In this section, you'll create two tables, a primary key in each table, and a few rows of sample data. You'll also
create a foreign key to specify how records in one table correspond to records in the other table.
Create the Customers table
1. In Ser ver Explorer , expand the Data Connections node, and then expand the SampleDatabase.mdf
node.
If you can't expand the Data Connections node, or the SampleDatabase.mdf connection is not listed, select
the Connect to Database button in the Server Explorer toolbar. In the Add Connection dialog box,
make sure that Microsoft SQL Ser ver Database File is selected under Data source , and then browse
to and select the SampleDatabase.mdf file. Finish adding the connection by selecting OK .
2. Right-click on Tables and select Add New Table .
The Table Designer opens and shows a grid with one default row, which represents a single column in the
table that you're creating. By adding rows to the grid, you'll add columns in the table.
3. In the grid, add a row for each of the following entries:

C O L UM N N A M E DATA T Y P E A L LO W N UL L S

CustomerID nchar(5) False (cleared)

CompanyName nvarchar(50) False (cleared)

ContactName nvarchar (50) True (selected)

Phone nvarchar (24) True (selected)

4. Right-click on the CustomerID row, and then select Set Primar y Key .
5. Right-click on the default row ( Id ), and then select Delete .
6. Name the Customers table by updating the first line in the script pane to match the following sample:
CREATE TABLE [dbo].[Customers]

7. Add an index constraint to the Customers table. Add a comma at the end of the Phone line, then add the
following sample before the closing parenthesis:

CONSTRAINT [PK_Customers] PRIMARY KEY ([CustomerID])

You should see something like this:

8. In the upper-left corner of Table Designer , select Update , or press Shift +Alt +U .
9. In the Preview Database Updates dialog box, select Update Database .
The Customers table is created in the local database file.
Create the Orders table
1. Add another table, and then add a row for each entry in the following table:
C O L UM N N A M E DATA T Y P E A L LO W N UL L S

OrderID int False (cleared)

CustomerID nchar(5) False (cleared)

OrderDate datetime True (selected)

OrderQuantity int True (selected)

2. Set OrderID as the primary key, and then delete the default row.
3. Name the Orders table by updating the first line in the script pane to match the following sample:

CREATE TABLE [dbo].[Orders]

4. Add an index constraint to the Customers table. Add a comma at the end of the OrderQuantity line, then
add the following sample before the closing parenthesis:

CONSTRAINT [PK_Orders] PRIMARY KEY ([OrderId])

5. In the upper-left corner of the Table Designer , select Update , or press Shift +Alt +U ..
6. In the Preview Database Updates dialog box, select Update Database .
The Orders table is created in the local database file. If you expand the Tables node in Server Explorer,
you see the two tables:
If you don't see it, hit the Refresh toolbar button.
Create a foreign key
1. In the context pane on the right side of the Table Designer grid for the Orders table, right-click on
Foreign Keys and select Add New Foreign Key .

2. In the text box that appears, replace the text ToTable with Customers .
3. In the T-SQL pane, update the last line to match the following sample:

CONSTRAINT [FK_Orders_Customers] FOREIGN KEY ([CustomerID]) REFERENCES [Customers]([CustomerID])

4. In the upper-left corner of the Table Designer , select Update (Shift +Alt +U ).
5. In the Preview Database Updates dialog box, select Update Database .
The foreign key is created.

Populate the tables with data


1. In Ser ver Explorer or SQL Ser ver Object Explorer , expand the node for the sample database.
2. Open the shortcut menu for the Tables node, select Refresh , and then expand the Tables node.
3. Open the shortcut menu for the Customers table, and then select Show Table Data or View Data .
4. Add whatever data you want for some customers.
You can specify any five characters you want as the customer IDs, but choose at least one that you can
remember for use later in this procedure.
5. Open the shortcut menu for the Orders table, and then select Show Table Data or View Data .
6. Add data for some orders. As you enter each row, it is saved in the database.

IMPORTANT
Make sure that all order IDs and order quantities are integers and that each customer ID matches a value that
you specified in the CustomerID column of the Customers table.

Congratulations! You now know how to create tables, link them with a foreign key, and add data.

See also
Accessing data in Visual Studio

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy