KEMBAR78
PCB-Based Control Lab 01 | PDF | Dialog Box | Window (Computing)
0% found this document useful (0 votes)
8 views19 pages

PCB-Based Control Lab 01

This document outlines the objectives and requirements for Lab 1, which focuses on introducing Visual Studio and Visual Basic. Students will learn to install Visual Studio 2015 Community Version, create applications using Visual Basic, and complete various tasks for grading. The lab includes pre-lab requirements, in-lab tasks, and a basic introduction to programming concepts and user interface design in Visual Basic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views19 pages

PCB-Based Control Lab 01

This document outlines the objectives and requirements for Lab 1, which focuses on introducing Visual Studio and Visual Basic. Students will learn to install Visual Studio 2015 Community Version, create applications using Visual Basic, and complete various tasks for grading. The lab includes pre-lab requirements, in-lab tasks, and a basic introduction to programming concepts and user interface design in Visual Basic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

EE______IU

PC-BASED CONTROL LABORATORY

LAB 1
INTRODUCTION TO
VISUAL STUDIO AND VISUAL BASIC

Student: ..............................................................
Student ID: ..............................................................
Class: ..............................................................
Date: ..............................................................

Page 1 of 19
1. Objectives
Upon completion of this lab, you will able to:
 Install Visual Studio 2015 Community Version.
 Be able to create an application using Visual Basic.
2. Grading
 Pre-lab: Done everything in Pre-lab before the lab start (10/100 points).
 In-lab: Finish all in-lab tasks (90/100 points).
Note: Pre-lab tasks are requirements for in-lab work. If you didn’t finish them at home, you
won’t have enough time for in-lab work and you will probably lose more than 10 points pre-
lab.
3. Pre-lab Requirement
3.1. Pre-lab tasks:
3.1.1. Installing Visual Studio Community:
 Go to Visual Studio Community official site:
https://www.visualstudio.com/vs/community/
 Click on “Download Community 2015” as in the figure below.

Figure 1. Download Visual Studio Community from official site.


 Then install with default settings.
You can copy the installation from PCs in Lab, or you can downlad the off-line installation
file from the internet and share with your friends.
3.2. Reading:
3.2.1. Introduction to Visual Studio (VS):
“Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It
is used to develop computer programs for Microsoft Windows, as well as web sites, web apps,
web services and mobile apps. Visual Studio uses Microsoft software development platforms
such as Windows API, Windows Forms, Windows Presentation Foundation, Windows Store and
Microsoft Silverlight. It can produce both native code and managed code.”

Page 2 of 19
3.2.2. Introduction to Visual Basic (VB):
Visual Basic is a high level programming language that evolved from the earlier DOS version
called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. The code
looks a lot like English Language. Now, there are many versions of Visual Basic available in the
market, the latest being Visual Basic 2015 that is bundled with other programming languages
such as C#.
Visual Basic is a Visual Programming Language because programming is done in a graphical
environment. In VB, you just need to drag and drop any graphical object anywhere on the form
and click on the object to enter the code window and start programming.
In addition, Visual Basic 6 is Event-driven because we need to write code that performs some
tasks to response to certain events. The events usually comprise but not limited to the user's
inputs. Some of the events are load, click, double click, drag and drop, pressing the keys and
more. We will learn more about events in later lessons. Besides that, a VB Program is made up
of many subprograms or modules, each has its own program code, and each can be executed
independently; they can also be linked together in one way or another.
4. In-lab Requirement
4.1. Creating a new Winform
4.1.1. Create a new project
1. Open “Microsoft Visual Studio”.
2. From menu, select “File  New  Project…” (or using shortcut “Ctrl+Shift+N”) as
shown in Figure 1.

Figure 2. Creating new project.

3. The “New Project” window appear (Figure 3).


4. On the left side of the windows, in the “Installed” tab (area 1 of Figure 3):
 Navigate to:
“Templates  Other Languages  Visual Basic  Windows”
or
”Templates  Visual Basic  Windows”

Page 3 of 19
5. On the middle (area 2 of Figure 3):
 Choose “Windows Forms Application”.
6. On the bottom of the windows (area 3 of Figure 3):
 Rename your project to “Lab1_StudentName_StudentID” (Your real name and ID, not
the words “StudentName_StudentID”).
 The “Solution Name” will be your project’s name as default.
Note: Solution is a group of many projects, so in this step, you can choose another name
for it.
7. Click “OK” to finish.

1
2

Figure 3. Choosing the project type.

8. After a few seconds, the “Design” Tab appear (Figure 4). In “Design” Tab, it is the
default form (name “Form1”).
Note: This default form will open when you run the program. When you create more forms,
you can set which forms will be open as the program.

4.1.2. Drag-and-drop design:


 Visual Studio supports drag-and-drop design, which mean you just drag any control from
“Toolbox” and drop it onto the “Form”, the control will be created. You can also move
control to other location by dragging it.

Page 4 of 19
Figure 4. Toolbox window.
 In case, you can’t find “Toolbox” window, reopen it by clicking on “View  Toolbox” .

Figure 5. Open “Toolbox” windows.

4.1.3. Common controls:


There are plenty of controls in VB.NET, but as we just start learning it, there are a few
common controls and their usages.
Page 5 of 19
Name Control Description

Labels are used to display text. It doesn’t accept input


Label from the user. Often a Label is used to describe
another control.

TextBox Textboxes are used to get and display text.

A button allows users to perform some action defined


Button
by the programmer by clicking on it.

ComboBox allows users to select one element from a


ComboBox
list of items.

ListBox allows users to select one element from a list


ListBox
of items.

A radio button allows users to choose exactly one of


RadioButton
a predefined set of options.

Check box indicates a two-way choice or state


CheckBox
(true/false) which can be changed by users.

TrackBar allows users to select the number by


TrackBar
dragging the slider.

NumericUpDown allows users to select the number


NumericUpDown
by enterring the number or pressing Up/Down button.

TabControl allows applications to define multiple


pages for the same area of a window. Each page
TabControl
consists of a certain type of controls that will displays
when the user selects the corresponding tab.

Table 1.Common controls.

4.1.4. Control’s properties and events:


 When you click on an object, the “Properties” window will display all properties and
events of that object.
 The “Properties” window has 2 most important tabs: the “Property” tab and “Events” tab,
marked with number 1 and number 2 correspondingly in the figure below.

Page 6 of 19
1 2

Figure 7. Control’s properties and events.


Properties:
 Some common properties of controls:
o Name: All controls have “Name” property. The name of control will be used for
accessing it. The name can’t have space and special characters.
o Enable: All controls have “Enable” property. This property indicates if users can
interact with the controls or not. (Programmer can still access it in design process or by
code).
o Text: Most controls have “Text” property which is the text displaying on the controls
(such as Form, Button, TextBox, Label, RadioBox, CheckBox, …)
 Other important properties of controls:
o TextBox:
 Text: the text displays on or inputs in this TextBox.
 ReadOnly: indicates if this Textbox is read only and users can’t edit the text on it.
 PasswordChar: indicates the character to display for password input.
o ComboBox & ListBox:
 “Items”: the collection of items that user can chose from.
 “SelectedItem”: represent the item that the user chose from the list of items.
 “SelectedIndex”: indicate the index of item that the user chose from the list of items.
o RadioButton & Checkbox:
 “Checked”: indicates if radioButton/checkBox is checked or not.
o TrackBar & NumericUpDown:
 “Value”: the value (number) that this control displays.
 “Minimum”: the smallest number that this control allows.
 “Maximum”: the largest number that this control allows.

Page 7 of 19
o TabControl:
 “TabPages”: the collection of TabPages in this TabControl. You can add, remove or
change the order of tab pages in this property. You may add or remove Tab Page by
click on the small triangle as shown below.

Figure 8. Add or remove tab pages.


Events:
 Events are basically a user action like key press, clicks, mouse movements, etc., or some
occurrence like system generated notifications. Applications need to respond to events
when they occur.
 “Event Handler” is a function that tell how to respond to event. To create a new event
handler, move to “Events” tab and double-click on an event name.
 For example, after double-clicking on the “Click” event (as in Figure 7), a function call
“CalculateButton_Click” is created.
 Ussually, a new tab will be opened with the same name as “Design” tab.
 As you can see in the figure below, a new function call “CalculateButton_Click” is
created. It is the event handler of “Click”. In other words, it is what happens when user
click on “CalculateButton”.

Figure 9. New Event Handler is created.


4.2. Basic Syntax
The syntax of VB.NET is different from C so we must consider the basic syntax of VB.NET
before going to coding.

4.2.1. Operators
 Arithmetic Operators:

Operator Description

^ Raises one operand to the power of another

+ Adds two operands

- Subtracts second operand from the first

Page 8 of 19
* Multiplies both operands
Divides one operand by another and returns a floating
/
point result
Divides one operand by another and returns an integer
\
result
Modulus Operator and remainder of after an integer
MOD
division
 Comparison Operators:

Operator Description

^ Raises one operand to the power of another


Checks if the values of two operands are equal or not; if
=
yes, then condition becomes true.
Checks if the values of two operands are equal or not; if
<>
values are not equal, then condition becomes true.
Checks if the value of left operand is greater than the value
>
of right operand; if yes, then condition becomes true.
Checks if the value of left operand is less than the value of
<
right operand; if yes, then condition becomes true.
Checks if the value of left operand is greater than or equal
>= to the value of right operand; if yes, then condition
becomes true.
Checks if the value of left operand is less than or equal to
<= the value of right operand; if yes, then condition becomes
true.
 Logical/Bitwise Operators:

Operator Description

^ Raises one operand to the power of another


And It is the logical as well as bitwise AND operator.
Or It is the logical as well as bitwise OR operator.
Not It is the logical as well as bitwise NOT operator.
It is the logical as well as bitwise Logical Exclusive OR
Xor
operator.
It is the logical AND operator. It works only on Boolean
AndAlso
data.
It is the logical OR operator. It works only on Boolean
OrElse
data.
IsFalse It determines whether an expression is False.
IsTrue It determines whether an expression is True.
= Checks if the values of two operands are equal or not.
<> Checks if the values of two operands are equal or not.
Checks if the value of left operand is greater than the value
>
of right operand.
Checks if the value of left operand is less than the value of
<
right operand.

Page 9 of 19
Checks if the value of left operand is greater than or equal
>=
to the value of right operand.
Checks if the value of left operand is less than or equal to
<=
the value of right operand.

4.2.2. Common Types


 “String”:
Dim StudentName As String

 Integral types: SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong, Char
Dim StudentID As Integer

 Floating point types: Single, Double


Dim Salary As Double

 Boolean:
Dim status As Boolean

 Array:
Dim twoDarray(10, 20) As Integer 'a 2-D array of integers

4.2.3. Decision Making


 “If … Then” Statement:
If condition Then
[Statement(s)]
End If

Example:
If (a <= 20) Then
c= c+1
End If

 “If … Then … Else” Statement:


If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If

Example:
If (a < 20) Then
Console.WriteLine("a is less than 20")
Else
Console.WriteLine ("a is not less than 20")
End If

 “Select … Case” Statement:


Page 10 of 19
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select

Example:
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select

4.2.4. Loops
 “For … Next” Loop:
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]

Example:
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next

 “While … End” Loop:


While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While

Example:
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While

Page 11 of 19
4.3. Design a simple user interfaces:
4.3.1. Task 1:
 Requirement:
Design a following user interface:
- In “Basic Operation”:
Select number from (1) and (3) and the operator from (2) combobox.
When user click “Calculation” button, the result will be displayed below in a textbox.
- In “Quadratic Equation”:
Input a parameters of the quadratic equation in (6), (7) and (8) textboxes.
When user click “Solve”, calculate the answer and show on 2 textboxes below, and only
consider when the equation have real number answers.
Solve the equation even when a, b or c equal zero.

Click inside the tab page


to select it.

(2)
(1) (3)

(4)

(5)

(6) (7) (8)


(9)

(10) (11)

Figure 10. Create a new winform and a tabControl.

 Designing guide:
1. Drag “TabControl” into the Form.
Delete 1 “TabPage” and change the text of the tab page to “Basic Math”.
Note: When you click on the title of a tab page, tab control will be selected, not the tab
page it self. To select the tab page, click inside the tab page, not the title.
2. Dragging “Label”, , “TextBox”, “Button”, “NumericUpDown” and “ListBox” and into
the Form likes the figure above.

Page 12 of 19
3. Change “Text”, “Fonts” properties of labels, textboxes and buttons to match the above
example form.
4. Rename controls:
- Control 1: “FirstNumeric”
- Control 2: “OperatorListBox”
- Control 3: “SecondNumeric”
- Control 4: “CalculateButton”
- Control 5: “OperationResultTextBox”
- Control 6: “ATextBox”
- Control 7: “BTextBox”
- Control 8: “CTextBox”
- Control 9: “SolveButton”
- Control 10: “X1TextBox”
- Control 11: “X2TextBox”
5. Since results of operations are not allowed to edit, change the “ReadOnly” property of
“OperationResultTextBox”, “X1TextBox”, “X2TextBox” to “true”.
6. Change “Minimum” and “Maximum” of “FirstNumeric” and “SecondNumeric” controls
to -200 and 200, respectively.
7. Use “Items” property of “OperatorListBox” to add items to its list (“Add”, “Subtract”,
“Multiply” and “Divide”).
8. Resize the TabControl and the Form.
9. Create a “Click” Event Handler for “CalculateButton” and “SolveButton”.
10. Write code for CalculateButton_Click and SolveButton_Click

 Coding guide:
1. CalculateButton_Click coding steps:
- Create a variable call “result” with Double type to store the result of the operation.
- Use Select...Case structure to select the operator that the user chose in
“OperationListBox”, and execute the responding operation.
In case of division operation, check if divisor is 0 or not. If it is not 0 than, perform
the operation as normal. If it is 0, than display “Undefined” on the result textbox then
exit the function immediately by Return keyword.
- Than display the result on the “OperationResultTextBox”. In order to convert number
type (Integer, Short, Double, …) into String type, use ToString() function.
Example: result.ToString("0.00") will convert “result” to String with 2 place.
2. “SolveButton _Click” coding steps:
- Convert a, b, c from the texts of Textboxes, correspondingly.
- Since the text in textbox is String type and nothing guarantee that it is a number
representing in String type.
Page 13 of 19
To convert a text into a number, use the following code:
Double.TryParse(text, number)

If the conversion false, number will be 0.


In case, you know that text represents a number, you can use the code:
number = Double.Parse(text)

If the conversion false, error will occur.


- To calculate square root of a number, use:
root = Math.Sqrt(number)

If number is negative, root will be NaN (Not a number) because Math.Sqrt is not
support complex number. To check if root is a NaN or not, use Double.IsNaN(root)

 Sample Answer:
- SolveButton_Click Code:
Private Sub CalculateButton_Click(sender As Object, e As EventArgs) Handles CalculateButton.Click
Dim result As Double
If OperatorListBox.SelectedItem IsNot Nothing then
Select OperatorListBox.SelectedItem.ToString()
Case "Add"
result = FirstNumeric.Value + SecondNumeric.Value
Case "Subtract"
result = FirstNumeric.Value - SecondNumeric.Value
Case "Multiply"
result = FirstNumeric.Value * SecondNumeric.Value
Case "Divide"
If SecondNumeric.Value <> 0 Then
result = FirstNumeric.Value / SecondNumeric.Value
Else
OperationResultTextBox.Text = "Undefined"
Return
End If
End Select
OperationResultTextBox.Text = result.ToString("0.00")
End If
End Sub

- SolveButton_Click Code:
Private Sub SolveButton_Click(sender As Object, e As EventArgs) Handles SolveButton.Click
Dim a, b, c As Double
Double.TryParse(ATextBox.Text, a)
Double.TryParse(BTextBox.Text, b)
Double.TryParse(CTextBox.Text, c)
If a <> 0 Then
Dim delta As Double
delta = Math.Sqrt(b*b-4*a*c)
If Double.IsNaN(delta)
X1TextBox.Text = "NaN"
X2TextBox.Text = "NaN"
Else
X1TextBox.Text = ((-b + delta)/(2*a)).ToString("0.00")
X2TextBox.Text = ((-b - delta)/(2*a)).ToString("0.00")
End If
Else
If b <> 0 Then
X1TextBox.Text = (-c/b).ToString("0.00")

Page 14 of 19
X2TextBox.Text = ""
Else
If c <> 0 Then
X1TextBox.Text = "Null"
X2TextBox.Text = ""
Else
X1TextBox.Text = "Any Number"
X2TextBox.Text = ""
End If
End If
End If
End Sub

Page 15 of 19
4.3.2. Task 2
 Requirement:
Create a new TabPage next to “Basic Math” tab and name it “Dialog and Message Box”.
- In “Color Changing”:
When user change value of color (red, green, blue) by the (2), (3) or (4) trackbars, the color
of the form title (1) will be changed to that color.
- In “Open and Save File Dialog”:
When user click on “Open” button, a dialog will show up and allow user to select a text
file (*.txt) to open. If user chose a file and click “OK”, the file will be displayed on the
textbox (7) below.
When user click “Save” button, a dialog will show up and allow user to select where to
save the text file (*.txt). If user click “Save”, the text from the textbox (7) will save to that
file.
- In “Message Box”:
User select one type of Message (Notification (8), Warning (9) or Error(10)). User inputs
the title text and message text in (11) and (12) textboxes.
When user clicks “Display” button, a message box will show up with the same type and
text as it has been set up.

(1)

(2) (3) (4)

(5) (6)

(7)

(8) (11)
(9)
(10) (12)
(13)

Figure 11. Create a new tab page.

Page 16 of 19
 Designing guide:
1. Select “TabControl”. Click on the small triangle on top right of it. Click on “Add Tab”
link to add a new tab.
Change the text of the new tab page to “Dialog and Message Box”.
2. Dragging “Label”, “TextBox”, “Button”, “TrackBar” and “RadioButton” into the new
tab page likes the figure above.
3. Change “Text”, “Fonts” properties of labels, textBoxes, buttons and radioButtons to
match the above example form.
4. Rename controls:
- Control 1: “FormTitleLabel”
- Control 2: “RedTrackBar”
- Control 3: “GreenTrackBar”
- Control 4: “BlueTrackBar”
- Control 5: “OpenFileButton”
- Control 6: “SaveFileButton”
- Control 7: “FileContentTextbox”
- Control 8: “NotificationRadioButton”
- Control 9: “WarningRadioButton”
- Control 10: “ErrorRadioButton”
- Control 11: “TitleTextBox”
- Control 12: “MessageTextBox”
- Control 13: “DisplayMessageButton”
5. Select “RedTrackBar”, “GreenTrackBar” and “BlueTrackBar”, then change their
properties:
- Change “Maximum” property to 255
- Change “TickFrequency” property to 32
6. Select “FileContentTextBox”. Click on the small triangle on top right of it. Tick on
“MultiLine”. Than increase its height to be able to display more text.
7. Create a “ValueChanged” Event Handler for “RedTrackBar”, “GreenTrackBar” and
“BlueTrackBar”.
8. Write code for RedTrackBar_ValueChanged, GreenTrackBar_ValueChanged and
BlueTrackBar_ValueChanged

9. Create a “Click” Event Handler for “OpenFileButton”, “SaveFileButton” and


“DisplayMessageButton”.
10. Write code for OpenFileButton_Click, SaveFileButton_Click and
DisplayMessageButton_Click

Page 17 of 19
 Coding guide:
1. Color changing coding steps:
- When user change red, green or blue values the title color will be changed. Therefore,
three funtions RedTrackBar_ValueChanged, GreenTrackBar_ValueChanged and
BlueTrackBar_ValueChanged will behave the same way.

We create a function that change color of the title according to the red, green and blue
value, let call it ChangeColor().
In three ValueChanged events, we just call ChangeColor() back.
2. Open and Save File Dialog coding steps:
- In order to write or read file add Imports System.Io on the top the the file.

- To create an open file dialog:


Dim openFileDialog = New OpenFileDialog()

Set up the “Filter”, which determines the type can be selected and opened.
openFileDialog.Filter = "Text Documents|*.txt|All File Types|*.*"

Figure 12. The filter of a open file dialog.


Set “Multiselect” to false, to allow user to select one file only.
- Creating a save file dialog is similar to creating the open file dialog.
Set the “Filter” to the same as in open file dialog.
Set the “AddExtension” to true, which will allow computer to automatically add
extension to the saving file when user omits it.
3. Message Box coding steps:
- To create a message box use the structure:
MsgBox(MessageText, MessageType, TitleText)

The message type can be select through MsgBoxStyle.


They are many types of MessageType that you can choose, for example from left to
right are MsgBoxStyle.Information, MsgBoxStyle.Exclamation and MsgBoxStyle.Critical

Figure 13. Three types of message box.

Page 18 of 19
 Sample Answer:
- Color Changing Code:
Private Sub ChangeColor()
FormTitleLabel.ForeColor = Color.FromArgb(RedTrackBar.Value,GreenTrackBar.Value,BlueTrackBar.Value)
End Sub

Private Sub RedTrackBar_ValueChanged(sender As Object, e As EventArgs) Handles RedTrackBar.ValueChanged


ChangeColor()
End Sub

Private Sub GreenTrackBar_ValueChanged(sender As Object, e As EventArgs) Handles GreenTrackBar.ValueChanged


ChangeColor()
End Sub

Private Sub BlueTrackBar_ValueChanged(sender As Object, e As EventArgs) Handles BlueTrackBar.ValueChanged


ChangeColor()
End Sub

- Open and Save File Dialog Code:


Private Sub OpenFileButton_Click(sender As Object, e As EventArgs) Handles OpenFileButton.Click
Dim openFileDialog = New OpenFileDialog()
openFileDialog.Filter ="Text Documents|*.txt|All File Types|*.*"
openFileDialog.Multiselect = False
if openFileDialog.ShowDialog() = DialogResult.OK Then
FileContentTextBox.Text = File.ReadAllText(openFileDialog.FileName)
End If
End Sub

Private Sub SaveFileButton_Click(sender As Object, e As EventArgs) Handles SaveFileButton.Click


Dim saveFileDialog = New SaveFileDialog()
saveFileDialog.AddExtension = True
saveFileDialog.Filter = "Text Documents|*.txt|All File Types|*.*"
if saveFileDialog.ShowDialog() = DialogResult.OK Then
File.WriteAllText(saveFileDialog.FileName, FileContentTextBox.Text)
End If
End Sub

- Message Box Code:


Private Sub DisplayMessageButton_Click(sender As Object, e As EventArgs) Handles
DisplayMessageButton.Click
If NotificationRadioButton.Checked Then
MsgBox(MessageTextBox.Text, MsgBoxStyle.Information, TitleTextBox.Text)
ElseIf WarningRadioButton.Checked Then
MsgBox(MessageTextBox.Text,MsgBoxStyle.Exclamation, TitleTextBox.Text)
ElseIf ErrorRadioButton.Checked Then
MsgBox(MessageTextBox.Text,MsgBoxStyle.Critical, TitleTextBox.Text)
End If
End Sub

Page 19 of 19

You might also like