BeginArticle:
Unit1 First Steps
Section Vb.net Introduction
Section Download, and Instal VB.net 2008
Step01 Get Vb.net 2008 Installer
Step02 Download the Install executable
Step03 Install Vb.net
Section Configure Vb.net For Accessibility
Step01 The Options Window
Step02 The Environment Branch
Step03 The Projects And Solutions Branchh
Step04 The Text Editor Branch
Section Getting Context Help About The IDE
Unit2 Create A Winforms Project
Section Winforms Project Introduction
Section Create The WinformBasics Project
Step01 The Start Page
Step02 The New Project Dialog
Section Form1
Step01 Open Form1 in the "Forms Designer"
Step02 Set Form1 Properties
Section Add 2 New Folders To The WinformBasics Project
Section Save The Project
Section Deleting A Project
Note- Before you go on take a look at:
Appendix92 Useful Hot Keys
Appendix93 Some Accessible Techniques
Appendix91 FormsLayout - Pixel Math
End Note
Unit3 Build A Simple Calculator
Begin Unit3 Overview
Section Unit3 Concepts
Begin Unit3 Concepts Introduction
Begin Concept Classes And Objects
Begin Concept VB Variables
Begin Concept Variable Scope:
Block Scope;
Procedure Scope;
Class Scope;
Namespace Scope;
Choice of Scope;
Begin Concept Access Modifiers:
The "Public" Modifier;
The "Private" Modifier;
The "Protected" Modifier;
The "Friend" Modifier;
The "Protected Friend" Modifier;
Begin Concept The "If" Conditional Statement
Begin Concept Comparison And Logical Operators Intro
Begin Concept The "Comparison Operators"
Begin Concept The "LogicalOperators"
Begin Concept Methods And Procedures
Begin Concept Exception Handling
Exercise Creating A Calculator
Section Add the Globals Class File
Section Add the Logger.vb Class File
Section Add The MathOperations Class File
Section Design The MathForm Layout
Section Adding A New Form To The Project
Step01 Add MathForm, Set Properties And Add Load Event
Step02 Set "MathForm" As the Project Default Form
Section Add UI Controls to MathForm
Step01Add The Labels
Step02 Add The TextBoxes
Step03 Add The ListBox
Step04 Add And Wire Up The Button's Click Event
Begin Optional IntelliSense Example
Step05 Load The ListBox Using MathForm's Load Event
Section Test The Calculator
Exercise Number Formatting
Section Number Formatting Introduction
Section Add A DisplayFormatting() Sub to The MathOperations Class File
Section Add a FormatsButton to MathForm
Section Test The Number Formatting Sub
Unit4 Arrays, Looping And Intro To Binding
Section Looping And Intro To Binding Overview
Begin Arrays Overview
Begin Looping Overview:
The For Loop;
The While Loop;
The Do Loop;
The For Each Loop;
Begin Binding Overview
Begin MSDN Binding Summary
Exercise Build A FriendsForm
Section FriendsForm Introduction
Section The WBFriendNames.txt File
Step01 Add WBFriendNamesPath To Globals
Section Design The FriendsForm Layout
Section Add The Form And Set As Start Form
Section Add UI Controls
Section Test The UI
Section Wire Up The Form
Step01 Initialize the LoadEvent
Step02 Wire Up The AddButton
Step03 Wire Up The DeleteButton
Step04 Wire Up The ChangeButton
Section Save Changes To WBFriendNames.txt
Unit5 Working With Strings
Section Working With Strings Overview
Section Concepts
Begin ConceptString Literals
Begin Concept String Variables
Section Create StringsForm - Overview
Section Design The Form Layout
Section Add StringsForm, Set Properties And Set As Startup Form
Step01 Add StringsForm, Set Properties And Add Load Event
Step02 Set "StringsForm" As the Project Default Form
Section Add UI Controls To StringsForm
Step01Add The Labels
Step02 Add The TextBoxes
Step03 Add And Wire Up The Button's Click Event
Section Notes On Exercise Procedures
Exercise Using The String Length Property
Exercise Using The Replace Method
Exercise Using The IndexOf Method
Exercise String Concatenation
Exercise Use The Trim Method To Remove Leading And Trailing Spaces
Exercise Pulling A Substring out of a longer string
Unit Document Appendix
Appendix90 Reference Materials
Section Arithmetic Operators
Section System.String Class
Begin String Class Overview
Begin String Class Properties
Begin String Class Methods
Section String Formatting Codes
Begin String Formatting Codes Overview
Begin Standard Numeric Format Strings
Begin Standard Format specifiers
Begin Custom numeric format Strings
Begin Custom numeric format Specifiers
Begin String Formatting Notes
Section System.Array Class
Begin ArrayClassOverview
Begin ArrayClassProperties
Begin ArrayClassMethods
Section System.IO.File Class
Begin File Class Overview
Begin File Class Methods
Begin Custom File enumerations
Begin Common I/O Tasks
Begin Common Directory Tasks
Section System.Exception Classs
Begin Exception Class Overview
Begin Exception Class Properties
System.Windows.Forms.BindingSource Class
Begin BindingSourceClassOverview
Begin BindingSourceClassProperties
Begin BindingSourceClassMethods
Begin BindingSourceClassEvents
Section System.Windows.Forms.Button Class
Begin Button Class Overview
Begin Button Class Properties
Begin Button Class Methods
Begin Button Class Events
Section System.Windows.Forms.ListBox Class
Begin ListBox Class Overview
Begin ListBox Class Properties
Begin ListBox Class Methods
Begin ListBox Class Events
Begin ListBox Notes
Section System.Windows.Forms.TextBox Class
Begin TextBox Class Overview
Begin TextBox Class Properties
Begin TextBox Class Methods
Begin TextBox Class Events
Appendix91 FormsLayout - Pixel Math
Appendix92 Useful Hot Keys
Begin WindowEyes
Begin Solution Explorer And General
Begin Forms Designer
BeginVB Code Editor
Begin IntelliSense
Appendix93 Some Accessible Techniques
Section The VB Code Window
Begin The Error List
Begin Using Collapsed Code Blocks Selecting, Copying, Replacing And Deleting Lines
Begin Selecting Large Blocks Of Lines
Begin Finding Variable or Object Declarations
Section The Properties Window
Begin Selecting A Control
Section The Forms Designer
Begin set focus to a visible or non-visible control
Appendix94 The Local MSDN Express Library
*****
Unit1 First Steps
Section Vb.net Introduction
Before you take step1...
Computer Programming involves taking real world problems and translating them into step by step statements on how to solve them.
It is very much like solving an Algebra problem or Trig Problem.
This Article does not attempt to teach you how to do this.
If you have had Algebra you might be able to pick up the process by observing the examples in this and other Articles in any of the computer languages.
This Article attempts to demonstrate how to get and work with VB.net using the IDE and how to understand a few basic OOP concepts in the process.
If you have ever done any code related work such as scripting or working with an advanced hand held calculator you will be more likely to get something out of this Article.
If not, you might find yourself frustrated when you try and build your own applications.
That said, you should get enough out of this Article to move on to other books or articles on the subject using a screen reader.
There are tons of things I did not touch on in this Article that you will want to learn.
This is just a Down And Dirty introduction to getting started with VB.net using Windoweyes.
When done you should at least have a little understanding of:
How to navigate the IDE;
How to use the VB Code Editor, the Properties Window and the Forms Designer;
How to Create A Windows Forms Project;
What a Class is and how to instantiate one;
How to add Procedures (Subroutines and Functions) to a class;
How to create a Windows Form and add UI Controls to it;
How to set properties for a Windows Form and the Controls you place on it;
Where to find MSDN Documentation for several referenced topics;
How to work with a few of the VB Language Statements and Methods;
And, a general idea of OOP when it comes to Classes, Procedures and Properties and how they are "Encapsulated" to form independent, reusable code blocks in VB.net.
Now, on with the show...
As the name implies Programmers will be writing their code in the Visual Basic Programming Language.
In the old days Programmers would write lines of computer code in a text editor like NotePad, compile the code into machine readable code using something called a "Compiler".
This "Compiled" code could then be run on a users computer.
While developing applications Programmers had to write hundreds, thousands and, for really big applications, millions of lines of computer code for any application.
Allot of these lines of code were redundant and the same code blocks had to be ReWritten over and over in the same Application.
As Programming progressed Programmers started setting up standards to make Program Creation and Maintenance faster, easier and less confusing.
They started "Modularizing" code blocks and putting them into modules they could just call from anyplace in the Application using just one or 2 lines of code instead of ReTyping the code block over and over.
As time and experience progressed Application Development went from the world of "Functional" design to the concept of using allot of "Modules" to hold blocks of code and using the Modules as a part of the design process.
This process morfhed into what today we call Object Orientated Programming (OOP).
In OOP we consider we are working with Objects which are just blocks of code related in some way.
For example...
A programmer might want to build a "Form" to display on a users computer screen.
Well, the "Form" is conceptually an object.
It has certain "Properties" like the Height and Width of the form to be displayed on the screen, a Background color and a color for the text to be displayed perhaps a black background with white letters.
Also, they usually had to write code for the form to build Buttons and Boxes so a user could enter some data and click a button to do something.
They found that the Buttons and Boxes also had to have "Properties like background color, foreground color, size and coordinates to position the control on the form.
The code to do things like Read from or write to a TextBox was often the same so they added the ability to automatically perform these standard operations.
They figured out that they could create blocks of code in modules that would allow for setting Properties and supply Event Processing for particular objects like Forms, buttons and TextBoxes.
They put the code related to each generalized "Object" in what is called a "Class".
So there is a Form Class, Button Class and a TextBox Class - along with many, many other classes.
These classes are kept in a Library by Microsoft and are referred to as the .net Framework Libraries.
Programmers can use these "Classes" by referencing them in their programs, setting a few properties and writing a few lines of code.
The Programmer could just create a "New" "Instance" of the Button Class, set it's color, size and position properties and write code to do something when the Button's Click Event Subroutine was automatically executed
as a result of the button having been clicked.
Note- A Subroutine is a block of computer code that has a Name Property and is kept inside a "Class" object.
Thus you have the Button "Class" with it's Properties and one or more "Subroutines" related to events like the button being clicked.
This is called "Encapsulation" and is one of the fundemental OOP concepts.
Thus, OOP "Class" Objects have Properties and Procedures "Encapsulated" in them and here we go...
End Section Vb.net Introduction
Section Download, and Instal VB.net 2008
Microsoft Provides a free, downloadable, version of VB.net 2008 for use by the public on their Download Center
Page.
Step01 Get Vb.net 2008 Installer
http://www.microsoft.com/downloads/details.aspx?familyid=f3fbb04e-92c2-4701-b4ba-92e26e408569&displaylang=en.
Read the System Requirements to ensure you are covered with your machine setup.
Note-
If installing on Windows Vista and you are running as a non-administrator, please
save the setup.exe to a local folder first. Then right-click on the setup.exe and
select “Run as administrator”.
Step02 Download the Install executable
Navigate down the page to the following text and the link.
File Name:
File Size
vbsetup.exe
2.6 MB
Download
Hit the Download Button and save the file to a folder.
Close your browser, you are done with the Download Webpage.
Step03 Install Vb.net
Click the vbsetup.exe file you saved and the installation begins.
Read the User Agreement and click I Accept.
Do not elect to install Sql Server if asked, uncheck the box if it comes up.
Answer any other questions, if asked, Click Install and wait...
The first message you are likely to get is one telling you that the Download is complete and you can disconnect from the internet.
The process is not complete, it has just downloaded the necessary elements and is still installing them.
It could take several minutes to complete the installation and the screen will not change during this installation.
The Installer does not tell you anything about it's progress until it is complete or encounters an error.
When done it will notify you, the screen will change with the message that it is done and vb.net is installed, or it will put up an error message.
So long as it says the Download is complete and you can Disconnect from the Internet, it is still installing.
Of course, if you have high speed internet and it takes more than say 15 minutes you might have a problem.
Once you are notified the installation is done you can find Vb.net 2008 under your Start Menu and put a shortcut to it on your desk top.
End Section Download, and Instal VB.net 2008
Section Configure Vb.net For Accessibility
This is a seemingly hard thing for beginners to do but it pays off big time when you learn to configure the IDE to your liking.
Take your time and slog through these steps before you try and use VB.net with your screen reader.
There are many settings that impact how the IDE reads with a screen reader and how it functions in general.
Below are some settings I am currently using and how to set them.
You will likely modify my settings as you gain experience and customize the IDE to your own liking.
For now, my settings should get you started.
Step01 The Options Window
Open Vb.net by clicking your new DeskTop Icon.
You will be put on the Start Page.
Hit the Alt key to open the Menu Bar.
Cursor to the Tools Menu and up or down cursor to the Options item and hit enter on it.
The Options Window comes up.
This is a TreeView of sorts with Tabbed Options for setting up the IDE.
If the Environment Branch is closed expand it by right cursoring on it and cursor down to the General Tab Group.
Tab around this group to where you hear the Show All Settings Check box and check it if not checked.
Now Close any open branches, I just left cursor to do this in Windoweyes.
Then Down Cursoring I hear...
Environment Closed one of 5
Projects And Solutions Closed 2 of 5
Text Editor closed 3 of 5
DataBase Tools closed 4 of 5
Windows FormsDesigner closed 5 of 5.
These are the major Branches in the Tree. We will expand a few of them one at a time and adjust some of the default settings. You can set the ones you want based on my settings, Jamal's documentation for using the IDE with JAWS or your personal preferences.
Step02 The Environment Branch
In the Options Window TreeView,
Right cursor on the Environment branch to expand it.
Cursor down to the General tab Group.
Tab across the items until you hear the "Show All Settings" checkbox and check it if not checked.
Continue tabbing in the General Tab and set the following options...
Set Window Layout to Tabbed Document by selecting this RadioButton.
Leave the items shown to the defaults or bump them to some number like 10 or 20.
I have the Show Status Bar option checked.
Close button affects Active Tool Window Only is checked.
AutoHide Button Affects Active Tool Window only is unchecked.
Animate Environment Tools is UnChecked.
Note- Animate is where controls fade in and out slowly and I think might mess with a Screen Reader so I turned it off.
Leave the RestoreFileAssociations Button alone.
Finally you are back to the Show All Settings CheckBox which should be checked.
Tab and click the OK button to save your changes and you are returned to the Start Page.
Hit the Alt Key to open the IDE's Main Menu.
Cursor to the Tools Menu, cursor up or down to the Options item and hit enter on it.
If the Environment Branch is not expanded, expand it and cursor down through the other items to get a feel for what you will be able to set under this Environment Branch.
I have Tab Items for...
AutoRecover, Documents, FindAndReplace, FontsAndColors, Help, ImportAndExportSettings,InternationalSettings, Keyboard, StartUp and TaskList.
Note that the help branch might take a few seconds to load when you cursor over it because it checks some files and online pages.
Now, Navigate to the Help SubMenu and expand it.
Note- It might take a few seconds for this item to appear in the list.
In the General Tab Group...
Show Help Using is set to "External Help Viewer"
Show Results Per Page 20
Show Topic Abstracts is checked.
Reuse Topic Window is Unchecked.
Highlight Search Terms is checked.
Include Partial Matches in Local SearchResults is checked.
Online Topic Language, English.
Online Tab Group...
When Loading Help Try Local First Then Online Radio Button is selected.
Under Search These Providers all 4 are checked.
There are 2 buttons I don't know what they do they just say button.
In the Options ListView...
I unchecked 4 guys from Roll... that is for ASP stuff.
I unchecked Asp Alliance again that is for ASP which is websites.
I UnChecked C# Corner, not related to VB.net.
I unchecked Developer Fusion in the UK.
I left everything else checked.
Tab and click OK if you change anything.
That is the end of the Environment Branch Settings.
Step03 The Projects And Solutions Branch
From The Start Page, Open the Options Window by clicking Options under the Tools menu.
collapse the Environment branch by left cursoring on it if it is open.
Expand the Projects And Solutions Branch by right cursoring it.
Cursor down to the General Tab Group.
Tabbing around...
Projects Location, leave as is.
User Project Templats Location, leave as is.
User Item Templates, leav as is.
Always Show Error List if Project builds with errors is checked.
Track active item in Solution Explorer is checked.
Show Advanced Build Configurations is Unchecked.
Always show Solution is unchecked.
Save New Projects when created is Unchecked.
Warn User when Project Location Is not trusted is checked
Show Output Window when build starts is unchecked.
Prompt for symbolic renaming when renaming files is UnChecked.
If you make any changes Click OK and you are returned to the Start Page.
If you returned to the Start Page click on Options under the Tools Menu and navigate down to the Projects And Solutions Branch and down to the
tab group called Build and Run.
Tabbing around this Tab Group...
BeforeBuilding ComboBox is set to Save All Changes.
Maximum Number Of Parellel Projects is set to 2.
Only Build Project and Dependencies on Run is Unchecked.
On Run, When Projects Are Out Of Date ComboBox is set to "Always Build".
On Run, When Build Or Deployment Errors Occur ComboBox is set to Prompt To Launch.
For New Solutions Use the Currently Selected Project for Startup is unchecked.
MsBuildVerbosity ComboBox is set to Minimal.
If you make changes Click OK.
Again, back to the Start Page.
Again open the Options Window and cursor down to the Projects And Solutions Branch then down to the
VB Defaults Tab Group.
Tabbing Around...
Option Explicit is on in the combo box.
Option Strict is off in that ComboBox.
Option Compare is set to Binary in that ComboBox.
Option Infer is set to on in that ComboBox.
This concludes the settings for the Projects And Solutions Branch so click the OK button to save the changes if you made any and return to the Start Page if you have not already done so.
Step04 The Text Editor Branch
Hit the Alt Key to open the menu Bar, click the Options item under the Tools Menu.
Cursor down the TreeView and close the Environment and the Projects And solutions Branches if open.
Expand the Text Editor Branch.
In the General Tab Group set...
Go To Selection Anchor After Escape is unchecked.
Drag And Drop Editing is checked.
Include Insertion PointMovements in Undo List is unchecked.
Automatic Delimiter Highlighting is checked.
Track Changes is UnChecked.
AutoDetect UTF 8 coding without signature is checked.
Display Selection margin is checked.
Display Indicator Margin is checked.
Display Vertical and horizontal check boxes are unchecked.
If you change anything click ok, and it's back to the start page.
ReOpen the Options window under the Tools Menu and navigate back to the Text Editor Branch and down past the
File Extensions tab to the
AllLanguages tab which is a sub branch and expand it.
In the General Tab...
AutoListMembers is unchecked.
Parameter Information is unchecked.
Note- Unchecking the above will still allow them to be used with intellisense
by hitting Ctrl+SpaceBar, Ctrl+Shift+SpaceBar or Ctrl+J
but they will just not pop up automatically which can cause problems with focus and a screen reader.
Enable Virtual Space is unchecked.
Word Wrap is Checked
Show Visual Gliffs for Word Wrap is unchecked.
Apply cut or copy to blank lines when there is no selection is checked.
Line Numbers is partially checked.
Enable single click navigation is partially checked.
Navigation Bar is unchecked
Click OK if you make any changes.
From the Start Page Navigate back to the Options Window,
TextEditor Branch,
down to the All Languages SubBranch
past the General Tab Group
to the Tabs Tab Group and...
Indenting Radio Button is set to None.
Tab size and indent size TextBoxes are left empty.
Tab, insert spaces radio is unselected and keep tabs radio is selected.
Click OK if you change anything.
Now we modify the specific settings for Visual Basic.
navigate back to the Options Window, to the TextEditor Branch and down to the
Basic SubBranch and expand it.
These settings are for the VB Text Editor. Any settings you change here will be reflected in the All Languages Tab Groups but changing something in the All Languages Tab Group will change these settings as well if I remember correctly.
In the General Tab Group...
Autolist Members and Parameters are unchecked.
WordWrap is checked.
Show Gliffs is unchecked.
Apply cut or copy to blank lines is checked.
Line Numbers is checked.
Single Click Navigation is checked.
If you made changes click the OK Button.
You are returned to the "Start Page".
navigate back to the Options Window, to the TextEditor Branch and down to the
Basic Language SubBranch.
Navigate down past the General Tab Group to the Tabs Tab Group.
Indenting is set to none,Tab size and indent size are set to 1.
Note- it would not allow me to set it to 0 or empty so I just picked 1 as the smallest indent.
Click OK if you made a change and from the Start Page navigate back to the Options Window, Back to the Text Editor Branch and back down in the VB Language Branch past the Tabs Tab Group to the
VB Specific tab group...
Automatic Insertion of End Constructs is checked.
Pretty Listing is unchecked.
Note- The above features can make your code look nice and dynamically add end constructs to statements but the pretty listing makes the code hard to work with in Windoweyes.
Enable Outlining Mode is checked.
Automatic Insertion interface and must override members is checked.
Show Procedure Line Seperators is unchecked.
Enable Error Correction Suggestions is Unchecked.
Note- The above was an attempt to reduce how often that bloody Error Window automatically pops up while trying to work in the text Editor with a Screen Reader.
Tab to ok and click it to save your settings for the Text Editor.
This is the end of the Text Editor Settings for use with this Article.
End Section Configure Vb.net For Accessibility
Section Getting Context Help About The IDE
When you want help or a description of something while working in the IDE...
hit Shift-F1. If nothing happens try just F1.
A Browser Window should open with Links and Details about the object you have focus on or it's parent window if help is available for the item selected.
If you do not get links and details but a message about online documentation or downloading, ReDraw the Screen ( Insert-BackSlash ) In WindowEyes.
This should then show details about the area in the IDE in which you are working with and links to get more details about specific items.
For Example...
You can use this technique while setting up the IDE Settings by opening the Options item under the Tools Menu. Then navigating to some setting, hitting Shift-F1 and, or, F1, then Insert-BackSlash (For Windoweyes) to redraw the screen and you can read about all the settings and get details on the one you have focus on to see what it does.
End Section Getting Context Help About The IDE
End Unit1 First Steps
Unit2 Create A Winforms Project
Section Winforms Project Introduction
We now have our Integrated development environment ( IDE ) initially set up for accessibility.
In any of the Visual Studio Modules like C# or .net we as screen reader users want to set every possible window to be a Tabbed Document. This is because we can close Tabbed Documents easily by hitting the Ctrl+F4 HotKey combination.When we close a window it is removed from the work space. When we just hide a window it's active Tab Name is still on the work space. For some things if you mouse over them they will automatically open or expand without telling you. Hidden files can mess with a Screen Reader by overlapping windows we might be working in. So, we will usually want to be able to close windows instead of just hiding them.
We can set a window to be a Tabbed Document in a few ways...
Method 1,
Hit Alt to bring up the Main Menu Bar.
Look under the Window Menu for the item labeled "Tabbed Document" and note it's short cut key, mine is "t".
Whenever a new window comes up hit Alt+w then t
If the window can be set to a tabbed document it will be set.
Method 2,
go under the Window Menu cursor to and hit "Tabbed Document.
Method 3,
Right Mouse click the name of a window that is hidden or docked.
If there is an entry in the Context Menu PopUp hit enter on the Tabbed Document entry.
Sometimes windows, like the Task Window and others, are not listed in the list of open Windows under the Windows Menu.
Some of them can be set to "Tabbed Document" if they have focus even if not listed under the Window Menu.
Some Windows like the Text Editor and the Forms Designer do not seem to be able to be set but they close correctly out of the box so it is not necessary.
Lets see how this works.
Open VB.net by clicking your new DeskTop Icon.
The IDE opens in the Start Page. You can check it by reading the Title Bar ( Ctrl+Shift+T in Windoweyes ).
Hit the Alt key to bring up the IDEs main Menu Bar.
Cursor to the Window menu and cursor down through the options.
I hear...
New Window Disabled
Split Disabled
Floating
Dockable
Tabbed Document Checked
Auto Hide Disabled
Hide
New Horizontal Tabbed Group
New Vertical Tabbed Group
Close All Documents
Reset Window Layout
one Start Page Checked
two Solution Explorer
Windows...
You can see that in the list of open windows that the Start Page is the active window because it is checked.
The Solution Explorer window is open but is not the active window because it is not checked.
If you were to hit "Tabbed Document" in the above list the Active Window would be set.
Just hit escape twice to get back to the Start Page.
( The Start Page now has Focus)
Just hit Alt+w then T while focus is on the Start Page.
This should set the Start Page to be a "Tabbed Document".
Now try closing it by hitting ctrl+f4.
There are windows, dialogs or other objects that can be set to tabbed documents that might not appear in the list of open windows from time to time and we want everything possible set to be a Tabbed Document if we use a Screen Reader.
So whenever any window or dialog opens try hitting Alt+w then T or setting it under the Window Menu, even if not listed but the "Tabbed Document" is not disabled.
I will make note of this as we start working more in the IDE.
One last point, under the Window Menu I note that the short cut hot key is "l" to close all open windows.
This is a very handy shortcut hot key as well.
You would use it by hitting Alt+w then L.
So, close everything that is open.
Alt+w, l
When the work area is clean and I listen to the Tital Bar ( Ctrl+Shift+T in WindowEyes ) I hear...
Normal Microsoft Visual Basic 2008 Express Edition Normal
That tells me all windows are closed and the WorkSpace, actually a MDI Window, has focus.
If you have Vb.net Open then close it by hitting Alt+F4.
To Recap...
Set new windows you use to be "Tabbed Documents"
Alt+w then T
Close All open windows
Alt+w then l
Close a Tabbed Document Window
ctrl+f4
End Section Winforms Project Introduction
Section Create The WinformBasics Project
Step01 The Start Page
Open your IDE by clicking on your new DeskTop Icon.
You should be on the Start Page.
(Hit Alt+w Then t - Set Start Page To Tabbed Document.)
You will likely be in the Project ListView .
This is where all your projects you are working on or have created earlier will be listed.
It will be empty if this is your first Project.
Clicking a Project Name in this list will open that project so you can work on it.
Tabbing around the "Start Page" you might hear Project ... and again Project ... I hear this twice with Windoweyes. These are buttons that bring up dialogs. The first one is the Open Project dialog, the second is a Create New Project dialog. I never use them - just a preference.
I use the options under the File Menu.
Tabbing there are 3 List Controls with news and some links of general interest. Again, I never use them.
Tab and I am returned to the List of my Existing Projects.
Lets clean our Work Area before continuing.
Hit Alt+w then L to close all open windows.
Step02 The New Project Dialog
Hit Alt to open the IDEs Main Menu Bar.
Under the File Menu click New Project.
(The New Project Dialog Is displayed) Check it by reading the Title Bar if you want. (ctrl+shift+t in Windoweyes)
(Note- hitting Alt+w Windoweyes clinks since this dialog can not be set to Tabbed Document"
But, it works correctly out of the box)
the Escape Key or ctrl+F4 will close it.
Tabbing around this dialog I hear...
NewProject Templates ListView, This was the control in focus when the Dialog Opened.
Name This is a TextBox where you will type the Projects name. It has a default depending on which Project type was highlighted in the ProjectTemplates ListView.
Then the OK and Cancel Buttons followed by a LargeIcons Button and back to the ProjectTemplates ListView.
So, place focus in the ProjectTemplates Listview by tabbing back to it and cursor over the Windows Forms Application item, to highlight it, but do not hit enter or any action key yet.
Tab to the Name Box and change it to WinformBasics then tab and click OK.
In about 30 seconds you will find yourself in the Forms Designer.
Hit ctrl+shift+t in windoweyes to read the Title Bar.
Mine reads...
Normal VBWinformBasics - Microsoft Visual Basic 2008 Express Edition Normal.
Hit ctrl+shift+s to read the Summary.
Mine reads "Form1" which is the name of the Form being displayed.
This is the Forms Designer and by default the Default Form called Form1 is being displayed graphically.
Just hit Ctrl+F4 to close this window for now.
Hit Ctrl+Alt+L or click Solution Explorer under the View Menu to open the Solution Explorer Window.
( Hit Alt+w then t to set it to be a Tabbed Document)
The Solution Explorer is the main place where you will see all the Folders and files that make up your project.
When I cursor through it I hear...
VBWinformBasics Expanded
MyProject
Form1.vb closed
As you can tell this is a sort of TreeView of folders.
This is the basic project structure you will use to navigate your project's objects.
Note- There are some hidden folders you can make visible under the Project Menu but we will not need them yet.
End Section Create The WinformBasics Project
Section Form1
By default we have a Windows Form named Form1 in the project.
This is set as the Default form to be automatically displayed whenever the project is run.
If you run the project now Form1 would be displayed but there would be nothing visible except the Title Bar which would say "Form1".
We will now set some properties of Form1 like Background and Foreground colors, it's size and location when displayed on the screen.
We will use Form1 in a later Article to navigate between other Forms we will add to the project.
Hit Alt+w then L to clear your workspace.
Step01 Open Form1 in the "Forms Designer"
Hit Ctrl+Alt+l to open Solution Explorer.
Cursor to Form1.vb and hit enter on it.
( The Forms Designer opens with Form1 loaded in it )
This window might take a few seconds to load.
You can tell by reading the Title Bar and the Window Summary.
My Title Bar (ctrl+shift+t)...
Normal WinformBasics - Microsoft Visual Basic 2008 Express Edition Normal.
My Summary (ctrl+shift+s)...
Form1.
You are now in the "Forms Designer".
( do not try and set it to be a Tabbed Document, it works correctly out of the box)
This is where we will add User Interface controls, like buttons and TextBoxes, and set their properties.
Step02 Set Form1 Properties
We can set the properties of Form1 from the "Properties Window".
You can open the "Properties Window" from under the View Menu or by hitting F4 while in the Designer.
Hit F4 to open the Properties Window.
The "Properties Window" comes up with "Form1" loaded.
Note- You can cursor up and down the Properties list to ensure that Form1 is the loaded control by checking the Name Property or the Text Property.
The Name and Text properties should say Form1.
See below if not sure about if you are in the Properties List on this Dialog.
Tabbing around the Properties Window I hear...
An EditBox to enter or change the Text Property.
A selectable ComboBox with a list of objects related to Form1.
Note- If you click one of the objects in this list you will be working on the properties for that object.
A toolBar, cursoring I hear...
Catagorized Button,
Alphabetical Button,
Properties Button,
and Events Button
then, Text Form1 so I am back into the Properties list.
You can up and down cursor to read the properties in the Properties List.
Note- the properties list is actually a Custom control that combines features of a table, a list and a TreeView.
For some properties you can tab once and type values in an EditBox.
For some properties the EditBox is actually a ComboBox where you can type a value or up or down cursor to select a value.
For some properties you can tab past the EditBox to a Browse Button that will bring up a Dialog to help you select values.
Tab into the list of properties,
Go to the top of page and start cursoring down the list and set...
Backcolor: Navy
Note- This EditBox is actually a ComboBox. You can type in "Navy" or cursor up and down to pick a background color.
After you type or pick a color from the list by highlighting it, just back tab to return to the Properties list.
Continue Cursoring and when you get to font It says something like...
Microsoft Sans Serif, 8.25pt closed.
If you tab you hear the current font setting (the above setting) in the edit box.
You can change it in the EditBox manually if you want.
Tab Again and you hear Browse... Dialog Button.
This button brings up a Dialog with Lists of options you can choose for most of the Font Defaults including the Font Name.
Note- if you change the size using this Dialog it will default to the Point Unit Measurement.
I like to set some of the Properties in the following way...
Cursor to the Font Branch,
Expand the Font Branch by right cursoring it.
If you cursor up and down you hear the following settings, or the ones for your system...
NameMicrosoft Sand Sarif
Size 8.25
Unit Point
Bold False
GDICharSet 0
GdiVerticalFont False
Italic False
StrikeOut False
Underline False
Cursor toSize, Tab and set it to 12 in the EditBox by replacing 8.8 manually - just type in 12.
Then BackTab to the Properties List to set that value.
Cursor down to Unit, tab past the edit box to the Browse Button and select Pixel from the ListView list of Font measurement unit types by hitting enter on it.
You are returned to the Properties List with the Font Type set to Pixel .
If you Left Cursor to close the Font Branch,
The Font Property Now Reads...
Microsoft Sans Serif, 12px
Continue cursoring to the Forecolor Property tab to the EditComboBox and either select or type in white.
Back Tab to the properties List to set the change.
Cursor Down to size and set it to 1000, 700 in the EditBox.
Note- My Screen Resolution is 1024 by 760 Pixels so I just picked 1000 by 700 as a nice big box that will fit on my screen.
Back Tab to the Properties list.
Continue cursorring down to Start Position and tab to the Browse button and click it.
Select Center Screen and hit enter.
Note- This means the Window will be centered on the screen whenever it is displayed.
You are returned to the Properties list.
( hit Alt+w then T - set it to Tabbed Document)
Hit CTL+F4 to exit the properties window and return to the Forms Designer.
Hit CTL+F4 again and answer yes to the prompt to save the changes.
If we hit ctl+f5 to run the project a centered black rectangle would basically fill the screen with the text "Form1" in the title Bar.
If you actually hit F5 you need to hit Alt+F4 to close the Test Environment and return to the IDE WorkSpace.
This is our first form. It has no controls on it so it just looks like the screen has turned Navy except for a little space around the edges and a line along the top that says "Form1".
Hit Alt+w then L to close all open windows and save your work.
If you did not set the Properties Window to be a Tabbed Document you can hit Enter on Form1.vb to open the designer,
Then f4 for the properties Window.
Hit Alt to open the Menu Bar, See if the Properties Window is active, checked, and if so, cursor to and check the Tabbed Document CheckBox if not disabled for this window.
Then hit Alt+w, then L to close all open windows and save your work when asked.
Either that, or just open the Properties window under the View Menu and hit alt+w then t.
End Section Form1
Section Add 2 New Folders To The WinformBasics Project
We will be writing some VB Classes and add additional forms to demonstrate some programming techniques.
To keep them out of the way in Solution Explorer we will put them in new folders called...
"UserCode" and "UserForms".
Then we can keep these folders closed when not working on one of the new forms or new VB Code "Class" files.
Hit ctrl+alt+l to open Solution Explorer.
Make sure none of the SubFolders are expanded.
Then cursor to the Root Directory "WinFormBasics".
Hit Alt and Under the Project Menu hit enter on New Folder".
The New Folder Dialog comes up.
( This dialog does not need to be set to a tabbed Document)
Tab and name the Folder UserCode then Hit Enter.
The UserCode Folder appears in Solution Explorer.
cursor back up to the Root folder "WinformBasics".
Hit Alt and Under the Project Menu hit enter on New Folder".
The New Folder Dialog comes up.
Tab and name the Folder UserForms then hit enter.
The UserForms folder is added to Solution Explorer.
If necessary hit ctrl+alt+l to open Solution Explorer.
It should now look like...
BeginView:
WinformBasics
My Project
UserCode
UserForms
Form1.vb
EndView:
Note- Form1.vb is not under the UserForms folder.
We will leave it outside this folder but put our own Forms inside it as we build them.
If you make a mistake and want to delete one of the new folders,
Place your cursor on it and hit the delete key.
The root folder "WinformBasics" is the Level 1 folder and the folders directly under it should all be Level 2 folders.
Of course, if you expand a level 2 folder, all the folders inside the level 2 folder would be level 3 folders and so on.
We want the UserForms and the UserCode folders as level 2 folders just like the My Project folder or the Form1.vb file.
Note- Form1.vb is actually a hybrid file / folder in this Tree Directory and we will look at it later.
End Section Add 2 New Folders To The WinformBasics Project
Section Save The Project
Hit Alt+F4 to close the project.
The IDE sees you have not saved it yet so a "Close Project" popup message asks you if you want to save it, click Save.
The Save Project Dialog window comes up.
( Again, the dialog does not need to be set to Tabbed Document)
We need a name and a Location to save the project.
The name winformBasics is already in the Name EditBox so tab to the location ComboBox.
Note- To keep file paths simple we will just add the project to the "C:\" directory.
The default directory is likely inside your My Documents folder under the Visual Studio 2008 folder.
If you do not use the "c:\" path you will have to make adjustments to some of the code in this Article.
Type...
c:\
Tab and ignore the Solution Name EditBox.
Tab and UnCheck Create Directory For Solution if checked.
Note- The Solution CheckBox creates a second folder layer we don't need.
tab and click the Save Button.
The IDE is closed and the VBWinformBasics Project has been created.
You can now navigate to the project in Windows Explorer to see the actual Folders and Files that make up our project.
Never change any of them in this way, always work in VB.net unless you know what you are doing.
End Section Save The Project
Section Deleting A Project
Note- If you do this step remember to go back through this tutorial to ReCreate the project.
This is just for reference purposes if you ever want to start over.
You can not delete a project directly from within the iDE.
To delete a project you go to the folder where it resides, delete the Project Folder and then go back into the IDE and try to open the project by clicking it in the ListView on the Start Page.
A PopUp Window will ask you if you want to remove the Directory Entry for the Project, click yes and the project entry is removed from the IDE's Project ListView on the Start Page.
That is how you delete projects in Visual Studio.
End Section Deleting A Project
End Unit2 Create A Winforms Project
Unit3 Build A Simple Calculator
Begin Unit3 Overview
To demonstrate some fundementals we will build a simple Arithmetic Calculator.
We will add 3 Classes to WinformBasics under the UserCode folder...
Logger.vb
Globals.vb
MathOperations.vb
These Class Files will hold the VB code necessary to perform some functions for this Unit and beyond.
We will then add a new form to WinformBasics...
MathForm.vb
We will add the following UI controls to MathForm...
FirstNumberLabel
SecondNumberLabel
AnswerLabel
FirstNumberTextBox
SecondNumberTextBox
AnswerTextBox
OperationListBox
CalculateButton
We will use the FirstNumberTextBox and SecondNumberTextBox to enter numbers used with a math operation like "Add", "Subtract" and so on...
The OperationListBox will hold a list of the operations so we can select one.
The Labels will provide label text for the boxes.
Finally, the CalculateButton will cause the selected operation to be executed.
End Unit3 Overview
Section Unit3 Concepts
Begin Unit3 Concepts Introduction
For more information on any of the concepts research can be conducted from the MSDN Local Library under the Help Menu, MSDN Online Documentation Pages or by Googling specific KeyWords of interest.
Many MSDN Documentation URLs are provided in the Reference Sections.
End Unit3 Concepts Introduction
Begin Concept Classes And Objects
A Class is a container for data and code.
A Class has "Properties" and "Methods".
A "Property" is a characteristic of the class.
For example...
A Button Class would have properties for...
A Name,
Background and ForeGround Color, Height and Width, Location on the Form and a "Text" Property to display the button's function to a user.
The action code is referred to as methods and can be a Subroutine or Function.
For Example...
For a Button Control there would be a Subroutine that gets executed whenever the button is clicked.
All the Methods and Properties related to the Object or Category are Encapsulated within the Class.
Classes are the heart and soul of an object-oriented language.
You will find yourself using classes whenever you write even the simplest of programs in Visual Basic .NET.
The Microsoft .NET Framework makes extensive use of classes,and so will we as Programmers.
Below are some common uses of classes...
Wrapping up "Encapsulating" the representation and set of operations you perform on a database table,
for example adding, editing, deleting, and retrieving data.
Wrapping up "Encapsulating" the set of operations and data for dealing with text files such as reading, writing, and indexing the lines of text within the file.
Wrapping up "Encapsulating" all global variables in a program into properties within a class.
You add a Class to your project by clicking "Add Class in the Add New Item Dialog.
We will be doing this in this tutorial.
The class will appear as an entry under the Solution Explorer list of Project items as a vb file.
A Class vb file might look like...
Class MyClass
Public Sub DeleteCustomer( Name As String )
[VB Code would go here]
End Sub
End Class
To execute the DeleteCustomer Sub from someplace else in your application you would
Instantiate MyClass as an object and call the DeleteCustomer Sub passing the name of a customer to be deleted as follows...
Dim oMyClass As New MyClass
oMyClass.DeleteCustomer( "John Smith")
You use the "New" KeyWord to instantiate something making it an "Object".
Classes that you use allot can be defined as holding Shared" objects like variables, Properties, subs and functions.
You do not have to "Instantiate" these Classes before you can use them as "Objects".
This is the case with many of the most commonly used methods in the .net Class Library.
End Concept Classes And Objects
Begin Concept VB Variables
Conceptually VB variables are similar to variables in Algebra.
A variable holds data.
x = 5
y = 7.5
z = "Some Text to store."
and so on...
VB variables have to be stored and recognized by a computer.
Therefore they require storage in some format inside the computer and, as a result, have diferent characteristics depending on what type of data you are storing, string data, numeric data or other types of data.
A variable has a Name, x, y, z, and so on...
You can make up pretty much any name for a variable.
x = 10
MyNumber = 10
MyThingy = any number
AnotherThingy ="A string of characters,"
You define a Variable in VB by using the "Dim" and "As" KeyWords.
The below 3 VB statements define 3 variables.
Dim MyCar As String = "Ford"
Dim NumberOfTires As Integer = 4
Dim CarsPrice As Decimal = 13000.99
The text enclosed in quotes above is called a String Literal and,
the variable with the name of "MyCar " is called a String Variable.
The "=" operator is called the Assignment operator when used to define a variable with the VB Dim Statement.
Dim SomeNumber As Integer = 0
Dim MyText As String = "SSome Text Goes Here"
The 2 VB Keywords "Dim" and "AS" are generally used to define a variable in VB.net.
So, when we want to use a variable we need to define it by telling the computer the name of the variable and what type of data it will hold.
We will be working with only a handful of DataTypes in this article.
Integer, Decimal and Boolean.
There are several more "Data Types".
You can find them detailed at...
http://msdn.microsoft.com/en-us/library/47zceaw7(VS.90).aspx
End Concept VB Variables
Begin Concept Variable Scope:
The scope of a declared element is the set of all code that can refer to it without qualifying it.
By "Qualifying" we mean putting the InstanceName or ClassName of where the variable is defined on the left of a period before the Variable Name.
Example...
If I have a Variable defined in one class and want to use it from another Class I would qualify it with the name of the Class Object as follows...
MyClass.MyVariable = something
or
Something = MyClass.MyVariable
If the variable is in "Scope" it does not need to be qualified as follows...
MyVar = something
something = MyVar
A Project can be considered of consisting of objects that are at diferent levels much like a Directory of Folders.
The highest level is the "Namespace" level followed by the
"Class" Level Objects followed by the
"Procedures" Level objects followed by
"Block" Level objects.
By default where you define a variable (element) determines the scope of the variable.
Namespace scope;
Available to all code in the namespace in which it is declared.
This means if you define a variable outside of a "Class" it will be available to any of the Classes, Procedures and Blocks inside that namespace.
Class Scope;
Available to all code within the Class in which it is declared
That is, All Procedures and Blocks within the Procedures.
Procedure scope;
Available to all code blocks within the procedure in which it is declared
lock scope;
Available only within the code block in which it is declared.
Specifying Scope and Defining Variables;
You specify the scope of an element when you declare it.
The scope can depend on the following factors...
1) The regionin which it is defined,
( NameSpace, Class, Procedure or Code Block).
2) The access level you declare for the element using one of the "Access Modifier" KeyWords,
A couple are "Public" and "Private".
More on "Access Modifiers" in the next Section.
Levels of Scope:
A programming element is available throughout the region in which you declare it.
All code in the same region can refer to the element without qualifying its name.
Block Scope;
A block is a set of statements enclosed within initiating and terminating declaration statements, such as the following...
Do and Loop
For [Each] and Next
If and End If
Select and End Select
Try and End Try
While and End While
With and End With
If you declare a variable within a block, you can use it only within that block.
In the following example, the scope of the integer variable
cube
is the block between
If and End If, and you can no longer refer to cube
when execution passes out of the block.
Copy
If n < 1291 Then
Dim cube As Integer
cube = n ^ 3
End If
Note
Even if the scope of a variable is limited to a block, its lifetime is still that
of the entire procedure ( Subroutine or Function) within which it is declared.
If you enter the block more than once during the procedure,
each block variable retains its previous value.
Once the Subroutine or function is exited the localy defined variables are destroyed.
Procedure Scope;
( subroutines and Functions)
An element declared within a procedure is not available outside that procedure.
Only the procedure that contains the declaration can use it.
Variables at this level are also known as
local variables.
You declare them with the Dim Statement.
Procedure and block scope are closely related. If you declare a variable inside a
procedure but outside any block within that procedure, you can think of the variable
as having block scope, where the block is the entire procedure.
Note
All local elements, even if they are Static variables, are private to the procedure in which they appear.
You cannot declare any element using the
Public keyword within a procedure.
Class Scope;
You can make a variable a "Class Scope" variable by defining it inside a "Class" but outside of any of it's Procedures.
When you make a declaration at the "Class Level", the access level you choose using one of the
"Access Modifiers" determines the scope of the element or variable.
A "Public" Access Modifier makes the "Class Variable" available to other classes.
The "Private" Access Modifier means the variable is available to only the Class in which it is defined.
The Dim statement at "Class" level defaults to Private if you do not use any access Modifier level keywords.
In the following example, all procedures defined in the Class can refer to the string variable strMsg.
Public Class MyClass
Dim strMessage As String = "Hello World"
[Subs and functions]
End Class
Only the procedures and blocks inside this class can use the strMessage Variable because it's "Scope" defaults to Private.
Public Class Class1
Public strMessage As String = "Hello World"
[Subs and functions]
End Class
Any procedures or properties inside Class1 can access this variable without qualification so long as they are in this class.
Code outside this class can see and use this variable by Instantiating a copy of Class1 and qualifying the name of StrMessage with the Name of the Variable used to Instantiate the copy of Class1 as shown below.
Public Class Class2
Public Sub MySub()
Dim instClass1 As New Class1()
Dim LocalMessage As String = instClass1.strMessage
End Sub
End Class
Above we "Instantiated" a copy of Class1, more on this later.
Then we declared a local string variable called LocalMessage and assigned the value held in strMessage to it.
LocalMessage now holds the value "Hello World".
Note how we had to qualify the strMessage variable name with the class instance name.
instClass1.strMessage.
If we use variable"strMessage"
anyplace in "MySub()" sub we will not have to qualify it.
That is because it was defined in the sub and has Procedure Scope for the sub. It is a "Local" variable inside the sub.
Just remember that usually to use variables from other classes you will need to qualify them with an instance Name or, in the case of "Shared" variables, the Class Name.
This will become clear with further examples in this and other Articles.
Namespace Scope;
We will not use this scope to hold User Variables in this article.
Any objects or variables defined at this level is available to all lower levels.
Choice of Scope;
When you declare a variable, you should keep in mind the following points when choosing its scope.
Advantages of Local Variables
Local variables are a good choice for any kind of temporary calculation, for the following reasons...
Name Conflict Avoidance.
Local variable names are not susceptible to conflict. For example, you can create
several different procedures containing a variable called intTemp.
As long as each intTemp is declared as a local variable, each procedure recognizes only its own version of intTemp.
Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other procedures.
Memory Consumption,
Local variables consume memory only while their procedure is running. Their memory
is released when the procedure returns to the calling code. By contrast,
"Shared" and "Static" variables consume memory resources until your application stops running.
Minimizing Scope
In general, when declaring any variable or constant, it is good programming practice
to make the scope as narrow as possible (block scope is the narrowest). This helps
conserve memory and minimizes the chances of your code erroneously referring to the
wrong variable.
End Concept Variable Scope
Begin Concept Access Modifiers:
When you define a variable or any other object you can specify a "Access Modifier" in the opening statement.
A "Access Modifier" modifies the default scope of a variable or element.
Note- In this article we deal with "Private" and "Public" variables and Objects at the "Class" level only.
The documentation reflects this by omitting some uses of the NameSpace Level, The generalized Module Level and the Structure Level.
The access level of a declared element is the extent of the ability to access it, that is, what code
has permission to read it or write to it.
This is determined not only by where the element is Declared, but
also by the access level specified by one of the "Access Modifier" KeyWords if specified when the variable or element was declared.
The "Public" Modifier;
When used in a declaration statement specifies that the elements can be accessed from code anywhere in the same project, from other projects that reference the project,
and from any assembly built from the project.
The following code shows a sample Public declaration.
Public Class classForEverybody
The "Private" Modifier;
The Private keyword in the declaration statement specifies that the elements can be accessed only from within the same module, class, or structure.
The following code shows a sample Private declaration.
Private Sub MySub()
You can use Private only at module level. This means you can declare a private element inside a module,
class, or structure, but not at the level of a source file or namespace, inside an
interface, or in a procedure.
Note- At the module level, the Dim statement without any access level keywords is equivalent to a
Private declaration.
In this article we deal with "Private" and "Public" variables and Objects at the "Class" level only.
Note- The following are just for reference, we will not use most of them.
The "Protected" Modifier;
The Protected keyword in the declaration statement specifies that the elements can be accessed
only from within the same class, or from a class derived from this class.
The following code shows a sample
Protected Sub ForMyHeirs()
You can use Protected only at class level, and only when you declare a member of a class like a Subroutine or other element.
The "Friend" Modifier;
"Friend"
The Friend keyword in the declaration statement specifies that the elements can be accessed
from within the same assembly, but not from outside the assembly.
This means you can declare a friend element at the level of a source file or namespace, or inside an interface, module, class, or structure, but not in a procedure like a Sub or Function.
(We will not be doing anything with this Modifier).
The "Protected Friend" Modifier;
The Protected and Friend keywords together in the declaration statement specify that the elements can be accessed either from derived classes or from within the same assembly, or both.
You can use ProtectedFriend only at class level, and only when you declare a member of a class.
This means you can declare a protected friend element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure, or procedure.
(We will not be doing anything with this Modifier).
End Concept Access Modifiers:
Begin Concept The "If" Conditional Statement
What is conditional logic?
Conditional Logic is all about - saying what happens if one condition is met, and what happens if the condition is not met.
Visual Basic uses the KeyWords "If", "Then", "Else" for conditional Logic.
A typical "If" statement might look like...
If x > y Then
MessageBox.Show( "X is Greater than y")
Else
MessageBox.Show( "X is not greater than y")
End if
The "Else" KeyWord is optional in a If / End If statement.
A "If" statement typically begins with the "If" KeyWord and ends with the "End If" KeyWord Statement.
The optional "Else" KeyWord indicates what to do if the "If" condition is not met.
After the If statement processing typically continues to the next line of vb codeafter the "End If" statement.
End Concept The "If" Conditional Statement
Begin Concept Comparison And Logical Operators Intro
The Conditional Operators allow you to refine what you are testing for.
They allow you to compare 2 things to see if they are equal, unequal or one is bigger than the other and much more.
We can break the Operators into 2 categories...
"Comparison Operators" that compare 2 conditions and,
"Logical Operators" which connect 2 conditions in some way.
End Concept Comparison And Logical Operators Intro
Begin Concept The "Comparison Operators"
The following are the comparison operators defined in Visual Basic.
BeginList:
"<" operator
"<=" operator
">" operator
">=" operator
"=" operator
"<>" operator
"Is" Operator (Visual Basic)
"IsNot" Operator
"Like" Operator (Visual Basic)
EndList:
These operators compare two expressions to determine whether or not they are equal,
and if not, how they differ.
Most of them are self explanitory.
The Is, IsNot, and Like Operators are diferent.
Note- We will not worry about the Is, IsNot, and Like Operators in this article.
The documentation is in the Reference Manual under the Comparison Operators.
URL:
http://msdn.microsoft.com/en-us/library/swf8kaxw(v=VS.90).aspx
Comparison Operator Examples
Operator
Meaning
">"
This symbol means Is Greater Than and is used like this...
If number > 10 Then
MessageBox.Show("The Number was Greater Than 10")
End If
"<"
This symbol means Is Less Than and is used like this...
If number <10 Then
MessageBox.Show"The Number was Less Than 10")
End If
">="
These symbols mean Is Greater Than or Equal to
, and are used like this...
If number >= 10 Then
MessageBox("The Number was 10 or Greater")
End If
"<="
These symbols mean Is Less Than or Equal to
If number <= 10 Then
MessageBox("The Number was 10 or less")
End If
End Concept The "Comparison Operators"
Begin Concept The "LogicalOperators"
Logical operators connect 2 Conditional expressions...
BeginList:
"And" Operator (Visual Basic)
"Not" Operator (Visual Basic)
"Or" Operator (Visual Basic)
"AndAlso" Operator
"OrElse" Operator
"IsFalse" Operator
"IsTrue" Operator
EndList:
If (X > y) And (a = b) then...
If ( x > y) Or (a = b) then...
If Not (a > b) then ...
Again Most of them are self explanitory.
We will only use the "And", "Or" and "Not" Keywords in this article.
The documentation is in the MSDN Reference Manual under "Logical Operators".
You can combine the Conditional operators with the KeyWord "AND" or the KeyWord "OR".
If (number > 5) And (number < 15) Then
Do Something
End If
"Or"
You can combine the Conditional operators with the KeyWord "OR".
If (number < 5) Or (number > 15) Then
Do Something
End If
Note- Put each condition in it's own pair of "( )" characters as you would in Algebra.
You can test for Negation using the Logical "Not" Operator or the Comparison Negation symbol "<>".
If MyNumber Not = 15 Then
Do Something
Else
Do Nothing
End If
If MyNumber <> 5 Then
Do Something
Else
Do something else
End If
I might use the "Not" operator when words are involved so it sounds better.
If Not IsNumeric( MyVariable ) Then
Do Something
End If
End Concept The "LogicalOperators"
Begin Concept Methods And Procedures
In Visual Basic .NET, Functions and Subroutines are refered to as"Methods" or "Procedures".
Examples...
Public Sub MySub( Parameters Go Here )
[Code goes here]
End sub
Public Function GetTax( PassedPrice As Decimal ) As Decimal
Dim Tax As Decimal = PassedPrice * .10
Return Tax
End Function
Note- The words "As Decimal" at the end of the "Function" opening Declaration says that this function will return a Decimal value when executed.
The words "As Decimal inside the parm list defines the DataType of the variable being passed into the Function.
You can add more than one variable by seperating them with commas...
Dim Sub MySub( FirstParm As String, SecondParm As Decimal, ThirdParm As Integer )
The syntax to call a Sub from another class...
ClassInstanceName.SubName( parm list )
for a function that returns a decimal value...
Dim MyNumber As Decimal = ClassInstanceName.FunctionName( Parms )
Note- There are the "ByVal" and ByRef" KeyWords you can include for each parm in the Parameter List but we will not use them in this Tutorial.
The parameters we use will use default Types automatically assigned by the compiler.
End Concept Methods And Procedures
Begin Concept Exception Handling
When a program runs it might encounter a problem An attempt to divide by 0 or try and perform some File Operation on a file with an invalid File Path.
In these cases the System throws a nasty little error message and crashes the program.
We can trap these errors and handle them more gracefully using something called a
"Try Catch" block.
There is a System Class called System.Exception that contains information about any system errors generated at RunTime.
A typical Try Catch structure might look like...
Try
[Statements of things to monitor for error]
Catch TryMessage As Exception
[Statements to execute if error occurs]
Finally
[Statements to execute if error or no error]
End Try
In a Try Catch block we can run a block of statements, like an attempt to open a file, inside the Try block.
If all goes well the file is opened and processing continues at the first statement after the ""End Try" KeyWord.
If there is an error attempting to open the file the statements in the "Catch" block are executed and processing continues after the "End Try" statement.
The TryMessage is just a variable name I made up to hold the instance of the system.Exception Class Object that holds the information about the error.
There is a "Finally" KeyWord that can be used to execute a block of code in either case, error or no error.
The MSDN Documentation Webpage URL and some reference materials are in the Reference section of this article.
We will use a Try Catch Block later in the sample code.
End Concept Exception Handling
Exercise Creating A Calculator
This is a rather long Article.
It contains allot of the basics we will use later.
If you get tired you can always hit Alt+f4 to close the VB.net project and save your work.
Then you can continue your work at a later time.
If you copy and paste the examples into your project for testing...
The "Sub" Declaritive opening statement
and the "Function" Declaritive Opening statements
will wrap so I used the "_" vb continuation character to put them on 2 lines.
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles TestButton.Click
EndCopiedCode:
This should take care of the wrapping problem when copying from a text file to the VB Code Editer.
Finally, you really don't have to close the Code Editor before you run a test.
Just put your code into the Subroutine or Function while in the Code Editer and you can click F5 to run the test with the current code.
When you hit Alt+F4 to close the test you will be returned to the Code Window.
I usually prefer closing the Editers and saving my work prior to testing anything.
If a crash messes up the IDE or forces a error shutdown of VB.net your work is not lost.
So far we have added a "UserCode" folder and a "UserForms" folder to the project.
Now we will add the following 3 Class Files to the UserCode folder.
Globals.vb
Operations.vb
Logger.vb
We will put variables we want to use throughout the project in the Globals File,
Math Operations and related code in the MathOperations.vb file and,
code to write lines of text to a log file in the Logger.vb file.
Each of these files will contain the code for their respective Class Definitions.
A note on syntax errors:
When you first open and work in the VB Code Editor you will be pretty much free of the Error Window.
After you test your program or explicitly call up the Error Window from under the View Menu it can get to be a pain.
The best way to use it is to Right Mouse double click on an error in the Error Window.
You will be taken to the line where the error occured in the VB Code Editor.
Fix the error and Cursor up or down.
Then bring up the Error Window again and repeat the process until you have 0 errors or warnings in the Error Window.
Then close the Error Window if you set it to be a Tabbed Document.
It is actually easier to fix all errors after a test , close the project and open it again for beginners to keep this window out of the way.
If the Error List Pops Up all the time you may need to check your IDE Settings under the Tools > Options window.
Finally, you can contact me or others on the Blind Programming e-list or the Blind-Geeks e-list for more help with that puppy if it becomes a problem.
Section Add the Globals Class File
We want to have some variables and elements that can be accessed from anyplace within our project.
These are referred to as "Global" variables.
As seen, we can put them as "Public" "Class" level variables.
Also, if we add the "Shared" KeyWord the Globals Class will not have to be Instantiated before use.
I use Globals for Error Messages andConstants as well as many other things in a typical project.
They will not change their values or be destroyed and that makes them quite useful when dealing with multiple forms.
Step01 Add Globals.vb
Hit ctrl+Alt+l to open Solution Explorer.
Cursor to UserCode.
Under the Project Menu click Add New Class.
( Alt+p, c on my machine)
change the name to
Globals.vb tab and click the Add button.
You are placed in the Code Editer with the Class opening and closing statements and they look like...
BeginCopiedCode:
Public Class Globals
End Class
EndCopiedCode:
Now, type in the following statements so the Class looks like...
BeginCopiedCode:
Public Class Globals
Public Shared CallStatus As Integer = 0
Public Shared ErrorMessage As String = ""
Public Shared Found As Boolean = False
Public Shared WBLogPath As String = _
"C:\WinformBasics\WBLog.txt"
' Constants
Public Const OK As Integer = 1
Public Const CallError As Integer = -1
End Class
EndCopiedCode:
Hit Ctrl+f4 to close the VB Code Editor and save your work.
The above variables have the "Public" "Access Modifier" which means they can be used anyplace in this project.
The "Shared" KeyWord means they will not be destroyed and will not require "Instantiation" before their use.
If you put your WBLog.txt file in another place use that file path.
The Path provided will put the WBLog.txt file inside my WinformBasics Directory and will appear in Solution Explorer with the path provided when the file is created.
End Section Add the Globals Class File
Section Add the Logger.vb Class File
In any program you will have the need to read and write files.
A Text File is a common way to keep track of messages or "Log" errors to have a record of later.
We will use a couple of methods in the "System.IO.File" class in the .net Library to do this.
Step01 Add Logger.vb
In Solution Explorer (Ctrl+Alt+l)
Cursor to UserCode.
Under the Project Menu click Add New Class.
( Alt+p, c on my machine)
change the name to
Logger.vb tab and click the Add button.
You are placed in the Code Editor with the Class opening and closing statements.
BeginCopiedCode:
Public Class Logger
End Class
EndCopiedCode:
Now, type in the following statements so the Class looks like...
BeginCopiedCode:
Imports System.IO
Public Class Logger
Public Shared Sub WriteLine( ByVal Line As String )
Try
File.AppendAllText( Globals.WBLogPath, Line )
File.AppendAllText( Globals.WBLogPath, vbCrLf )
Catch TryMessage As Exception
MessageBox.Show( "Exception in logger, " & TryMessage.ToString() )
End Try
End Sub
Public Shared Sub Clear()
File.Delete( Globals.WBLogPath )
WriteLine( "Initialized" )
End Sub
End Class
EndCopiedCode:
Hit Ctrl+F4 to close the Editer and save your work.
In the above code you see the "Imports" statement outside the "Class".
The "Imports" statement gives us a reference to the "members of the "File" Class in the .net library without fully qualifying it's file path.
For example...
We use
File.AppendAllText( Globals.WBLogPath, Line )
in the Logger WriteLine sub.
Without the Imports statement we would have had to use the fully qualified path to that method like...
System.IO.File.AppendAllText( Globals.WBLogPath, Line )
If you tried to use
File.AppendAllText( Globals.WBLogPath, Line )
without the Imports System.IO statement you would get a syntax error.
The only other thing in this code new to us is the "Try / Catch" block.
This block of code is used to trap system errors.
It begins with the "Try" KeyWord and ends with the "End Try" KeyWord statement.
The "Catch Keyword contains what to do if an error is encountered.
If an error is encountered the statements in the Try Block are "Rolled Back" so none of them impact the file.
We put statements we want to watch for errors between the "Try" and the "Catch KeyWords.
Try
File.AppendAllText( Globals.WBLogPath, Line )
File.AppendAllText( Globals.WBLogPath, vbCrLf )
Catch TryMessage As Exception
Above we are trying to use the File.AppendAllText class.
If an error is encountered at RunTime execution will be transferred to the first statement in the "Catch" block and no statements in the Try Block will impact our WBLog.txt file.
The "Catch" block begins with the "Catch" KeyWord followed by the name of a variable followed by the "As" KeyWord and the word "Exception" in this example.
I just invented TryMessage" for a variable name to hold the instance of the system generated "Exception" object That was created from the "Exception" Class when the error occured.
Catch TryMessage As Exception
MessageBox.Show( "Exception in logger, " & TryMessage.ToString() )
End Try
This way we display a message and can handle the exception so the Application will not crash if there is a error like an invalid file path.
The "vbCrLf" KeyWord means to append a carriage return and line feed to the end of the line.
Without this all lines would be appended as one long string instead of individual lines in the text file.
The ToString() method pulls the text out of the Exception Object, more on it later.
Now we can write a line of text to our WBLog.txt file as follows...
Logger.WriteLine( "Something to log")
We can clear the WBLog.txt file like...
Logger.Clear()
Note that we do not have to Instantiate the Logger Class since the Subs are declared with the "Shared" KeyWord.
We Use the Try Catch block extensively when using File IO methods or DataBase Operations because these are the places you are most likely to encounter Fatle errors at RunTime.
Hit alt+w then l to close all open windows and save your work.
End Section Add the Logger.vb Class File
Section Add The MathOperations Class File
We will need to have calculations to execute when we ask our Calculator to add, subtract or multiply numbers.
We can put these calculations, and any other items related to "Math Operations" in a single class.
We will add one Function for each Arithmetic Operation we want to perform.
Then, when a user asks to add 2 numbers we will call the appropriate Function in this class passing it a couple of numbers to add, subtract, multiply or divide.
The Function will perform the calculation and return the answer to the calling statement's result variable.
A call to the Add Subroutine from another place in our program might look like...
Dim Answer As Decimal = 0
Answer = Add( FirstNumber, SecondNumber)
After the Function "Add" finishes it places the calculated value into the Answer variable and processing continues in the calling module.
Hit ctrl+alt+l For Solution Explorer.
Place your cursor on the UserCode Folder.
Pick Add Class from under the Project Menu.
Name the class MathOperations.vb tab and hit the Add Button.
Modify the code to look like...
BeginCopiedCode:
Public Class MathOperations
Public Function Add( Number1 As Decimal, Number2 As Decimal ) As Decimal
Dim Answer As Decimal = Number1 + Number2
Return Answer
End Function
Public Function Subtract( Number1 As Decimal, Number2 As Decimal ) As Decimal
Dim Answer As Decimal =Number1 - Number2
Return Answer
End Function
Public Function Multiply( Number1 As Decimal, Number2 As Decimal ) As Decimal
Dim Answer As Decimal =Number1 * Number2
Return Answer
End Function
Public Function Divide( Number1 As Decimal, Number2 As Decimal ) As Decimal
If number2 = 0 Then
Globals.CallStatus = Globals.CallError
Globals.ErrorMessage = "Attempt to divide by 0 in MathOperations.Divide"
Logger.WriteLine( "Fatle Error Encountered in MathOperations.Divide")
Logger.WriteLine("The Second Passed Parameter Is Invalid for this operation" )
Logger.WriteLine( "The value Passed was: " & Number2.ToString())
Return 0
End If
Dim Answer As Decimal = Number1 / Number2
Return Answer
End Function
End Class
EndCopiedCode:
Above we added Functions to process individual calculations.
You can put any number of statements in a function and call other subroutines and other functions from within the current function.
In the "Divide" Function I make sure a Divide by 0 can not occur by editing the variable to be used as the denominator.
If it is 0 I put some values into the Global Error Variables we built,
Write some lines about the error to WBLogger.txt and,
Return a 0 value as the answer.
Note- I test the CallStatus code in the calling module, the MathForm's CalculateButton_Click Event Subroutine, and if it is bad after executing this "Divide" Function I display a message to the user and allow the user to change the value in SecondNumberTextBox.
We will see how this is done shortly.
End Section Add The MathOperations Class File
Section Design The MathForm Layout
We want to layout a black area of 1000 by 700 so it looks OK and reads OK with a Screen Reader.
We want to group content by type or function and put things in the proper order.
We also want to make sure they read correctly with a Screen reader.
We will want to be able to enter 2 numbers, select some math operation and click a button to perform it.
Finally we want to read the answer.
I want the FirstNumberTextBox, SecondNumberTextBox and the list of math operations to select from close to each other.
Since the button will be clicked next and then the answer read I want them away from the first group and close to each other.
This way there is less mouse movement for sighted users and the controls flow in a logical visual sequence.
The controls we will need...
FirstNumberLabel and FirstNumberTextBox
SecondNumberLabel and SecondNumberTextBox
OperationListBox
CalculateButton
AnswerLabel and AnswerTextBox
The MathForm uses a font size of 12 pixels. Since any character, number, we type will not be wider than 12 pixels, most 10 or less,A TextBox lenght of 100 pixels will display about 10 characters including a decimal point which is fine for this article.
If you enter more it will scroll anyway so a TextBox length of 100 will do.
We will use the AutoGenerated heights for the Labels and TextBoxes.
We will put the labels immediately over each related TextBox aligned to the left edge of it's related TextBox.
To group the FirstNumber, SecondNumber and OperationListBox I will just put them in the upper left quadrant of the form.
FirstNumber and SecondNumber controls will be aligned horizontally with the OperationListBox below them.
I will arrange the CalculateButton and the answer controls vertically in the upper right quadrant.
Control Settings...
Name: FirstNumberLabel
Location: 50, 100
TabIndex: 1
Text: First Number
Name: FirstNumberTextBox
Location: 50, 100+Label Height
Size: 100, Use Compiler Default
TabIndex: 2
Name: SecondNumberLabel
Location: 200, 100
TabIndex: 3
Text: Second Number
Name: SecondNumberTextBox
Location: 200, 100+Label Height
Size: 100, Use Compiler Default
TabIndex: 4
Name: OperationListBox
Location: 50, 200
Size: 250, 400
TabIndex: 5
Name: CalculateButton
Location: 700, 100
TabIndex: 6
Text: Calculate
Name: AnswerLabel
Location: 700, 200
TabIndex: 7
Text: Answer
Name: AnswerTextBox
Location: 700, 200+ Label Height
Size: 100, Use Compiler Default
TabIndex: 8
Now, I have my controls positioned, sized and sequenced.
We will set the vertical positions of our TextBox controls when we see what default height is generated by the compiler for the Label Controls.
End Section Design The MathForm Layout
Section Adding A New Form To The Project
We will add a new Windows Form named MathForm, set some properties and add it's Load Event Subroutine.
Then we will set it as the Default Project Form in place of Form1.
Step01 Add MathForm, Set Properties And Add Load Event
Open Vb.net from your DeskTop Icon.
Hit enter on VbWinformBasics.
Hit ctrl+alt+l for Solution Explorer.
Close all open SubFolders.
Cursor to the UserForms folder.
When we drop a form into the project it will be added where the cursor is located.
Hit "Add Windows Form" under the Project Menu.
Name it MathForm and click the Add Form button
You are placed in the Designer.
Hit F4 for the Properties Window.
Set...
Backcolor: Navy
Font: (Expand the branch)
Ccursor toSize, Tab and set it to 12 in the EditBox.
Cursor to Unit, tab past the edit box to the Browse Button and select Pixel from the ListView list of Font measurement unit types by hitting enter on it.
Left cursor a few times to close the Font Branch.
Back in the PropertiesList, Cursor down to Forecolor and either select or type in white.
Cursor Down to size and set it to 1000, 700 in the EditBox.
Continue cursorring down to Start Position and tab to the Browse button and click it.
Select Center Screen and hit enter.
You are returned to the Properties Window list of properties for the form.
Back Tab to the ToolBar.
Right Cursor to the Events Button and click it.
Cursor to and click on the "Load" event.
You are placed in the Code Editor for the MathForm's Load Event.
Modify it so It looks like...
BeginCopiedCode:
Public Class MathForm
Private Sub MathForm_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
Logger.Clear()
End Sub
End Class
EndCopiedCode:
Hit Alt+w, l to close all open Windows and save your work.
MathForm.vb should now appear in Solution Explorer under the UserForms folder as a level 3 object.
The call to Logger.Clear will clear the WBLog.txt file when the MathForm is first loaded.
Step02 Set "MathForm" As the Project Default Form
By Default "Form1" will come up when we run the project.
We want to change that so MathForm comes up as the Default Form when the project is run.
Hit Alt to open the IDE Main MenuBar.
Under the Project Menu click the WinformBasics Properties.
Tabbing around the Settings Dialog I hear entries for...
Root Namespace, Application Type, Icon,StartUp Form, Assembly Information, View UAC Settings ButtonEnable Application Framework checkbox, Enable XP Visual Styles Checkbox, Make Single Instance Application , Save My Settings On Shutdown, Authentication Mode, ShutDown Mode, Splash Screen, View Application Events Button, Assembly Name, and back to the NameSpace box.
Tab to the StartUp Form which is likely "Form1" in the ComboBox.
Open the ComboBox, alt +down cursor, and hit enter on "MathForm"
Tab once and hit ctrl+f4 to close the Settings dialog.
Before we start testing we need to do one more thing.
If you set up the WBLog.txt file withthe the path to show up in the Solution Explorer as indicated in this article...
Under the Project Menu, cursor to and click the "Show All Files" item.
A couple of new folders will appear in the list and the form.vb files will now be expandable.
BeginList:
WinformBasics Expanded 8 items depth 1
My Project closed 1 of 8
References closed 2 of 8
bin closed 3 of 8
obj closed 4 of 8
UserCode closed 5 of 8
UserForms closed 6 of 8
Form1.vb closed 7 of 8
EndList:
We will not dig into these new additions until later.
Hit F5 to run the project.
Read the Title Bar.
Hit alt+f4 to close the Test and return to the development IDE.
If the Title Bar said Form1 and not MathForm go back and try setting the Start Form again.
I have found that sometimes the change does not take and I'm not sure why but trying it again usually fixed that.
Now close VB.net (Alt+f4) and save your work.
Open it again and WBLog.txt should appear at the bottom of the Solution Explorer list.
Hit enter on it to open it and the only line should read...
Initialized
Hit Ctrl+f4 to close the WBLog.txt file.
I am not sure why we have to close the project the first time we use the Logger to get WBLog.txt to show up in Solution Explorer but it is what it is.
After you do this once it works as expected and it is updated each time we run a test without closing the project again.
End Section Adding A New Form To The Project
Section Add UI Controls to MathForm
Step01 Add The Labels
In Solution Explorer hit Enter on MathForm.vb to open the Designer.
Hit Ctrl+Alt+x to open the ToolBox.
Cursor down to Label and hit enter to drop a Label Control on the Designer.
Copy it to the clipboard, ctrl+c then hit ctrl+v twice to paste 2 more Label Controls on the Designer.
Note- do not worry about where they are droppe.
Tab to Label1 and hit F4.
The Properties Window comes up with Label1 loaded.
Set...
Name: FirstNumberLabel
Location: 50, 100
TabIndex: 1
Text: First Number
Note- In the Size Property the height is 15 on my machine and I make a note of it.
Hit Ctrl+F4 to return to Designer.
Tab to Label2 and hit F4.
Set...
Name: SecondNumberLabel
Location: 200, 100
Text: Second Number
TabIndex: 3
Text: Second Number
Hit Ctrl+F4 To Close The Properties Window and return to Designer.
Tab to Label3 and hit F4.
Set...
Name: AnswerLabel
Location: 700, 150
TabIndex: 7
Text: Answer
Hit Ctrl+F4 To Close The Properties Window and return to Designer.
Step02 Add The TextBoxes
Hit Ctrl+Alt+x for the ToolBox.
Hit Enter on the TextBox element to drop a TextBox on the Designer.
Copy it and paste 2 more TextBox Controls on the Designer.
Note- do not worry about where they are droppe.
Tab to TextBox1 and hit F4.
Set...
Name: FirstNumberTextBox
BackColor: black
ForeColor: White
Location: 50, 115
Size: 100, 21 Leave Default Height)
TabIndex: 2
Note- I added the height of the Label (15 in my case) to the labels vertical location setting of 100.
Hit Ctrl+F4 To Close The Properties Window and return to Designer.
Tab to TextBox2 and hit F4.
Set...
Name: SecondNumberTextBox
Back Color: black
ForeColor: White
Location: 200, 115
Size: 100, 21 Leave Default Height)
TabIndex: 4
Hit Ctrl+F4 To Close The Properties Window and return to Designer.
Tab to TextBox3 and hit F4.
Set...
Name: AnswerTextBox
BackColor: black
ForeColor: White
Location: 700, 165
Size: 100, 21 Leave Default Height)
TabIndex: 8
Hit Ctrl+F4 To Close The Properties Window and return to Designer.
Step03 Add The ListBox
Hit Ctrl+Alt+x for the ToolBox.
Hit Enter on the ListBox element to drop a ListBox on the Designer.
Hit F4 and Set...
Name: OperationListBox
BackColor: Navy
ForeColor: White
Location: 50, 200
Size: 250, 400
TabIndex: 5
Hit ctrl+f4 to close the Properties Window and return to the Designer.
Note The height will automatically be adjusted to the highest integral number of items as defined by font size and padding.
Step04 Add And Wire Up The Button's Click Event
Hit ctrl+alt+x for the ToolBox, cursor down and hit enter on Button.
Hit F4 and set...
Name CalculateButton
Location: 700, 100
Text Calculate
TabIndex: 6
Hit Back Tab to the ToolBar, cursor to the Events Button and click it.
Cursor up or down to the click Event and hit enter.
You are placed in the code editor.
Modify the Code to look like...
BeginCopiedCode:
Private Sub CalculateButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles CalculateButton.Click
Dim FirstNumber As Decimal =0
Dim SecondNumber As Decimal = 0
Dim Answer As Decimal = 0
' Test For Valid Input Values
If Not IsNumeric( FirstNumberTextBox.Text ) Then
MessageBox.Show( "FirstNumberTextBox Is Not Numeric")
FirstNumberTextBox.Focus()
Return
Else
FirstNumber = CDec( FirstNumberTextBox.Text )
End If
If Not IsNumeric( SecondNumberTextBox.Text ) Then
MessageBox.Show( "SecondNumberTextBox is not numeric" )
SecondNumberTextBox.Focus()
Return
Else
SecondNumber = CDec( SecondNumberTextBox.Text )
End If
' Process The Request
' Instantiate a MathOperations Class Object.
Dim OperationsObject As New MathOperations()
If OperationListBox.SelectedItem = "Add" Then
Answer = _
OperationsObject.Add(FirstNumber, SecondNumber)
ElseIf OperationListBox.SelectedItem ="Subtract" Then
Answer = _
OperationsObject.Subtract(FirstNumber, SecondNumber)
ElseIf OperationListBox.SelectedItem = "Multiply" Then
Answer = _
OperationsObject.Multiply(FirstNumber, SecondNumber)
ElseIf OperationListBox.SelectedItem = "Divide" Then
Globals.CallStatus = Globals.OK
Globals.ErrorMessage = ""
Answer = _
OperationsObject.Divide(FirstNumber, SecondNumber)
If Globals.CallStatus <> Globals.OK Then
MessageBox.Show( Globals.ErrorMessage )
Logger.WriteLine( "The Following Error Was Returned to MathForm.CalculateButton_Click.")
Logger.WriteLine( Globals.ErrorMessage )
Logger.WriteLine( "ActionTaken: Let user Try Again")
SecondNumberTextBox.Focus()
Return
End If
Else
MessageBox.Show( "No Operation Found Matching Selected Item - Likely A Typo in CalculateButton ClickEvent")
Return
End If
AnswerTextBox.Text = Answer
AnswerTextBox.Focus()
End Sub
EndCopiedCode:
Hit Alt+w, l to close all open windows and save your
work.
Here we check which operation was selected in the If and ElseIf statements.
If none were selected ( The Else Block) that means that the literal in the ListBox did not match the literals we tested for and likely a typo.
This should not be a problem after the project goes into production but might help us during development or if the project is ever modified or extended.
In the Divide Block we create another If / End If statement block.
This is called a "Nested If" statement block.
It is nested inside the code block that begins with the statement,
ElseIf OperationListBox.SelectedItem = "Divide" Then
and ends with the statement,
Else
The block itself looks like...
If Globals.CallStatus <> Globals.OK Then
MessageBox.Show( Globals.ErrorMessage )
Logger.WriteLine( "The Following Error Was Returned to MathForm.CalculateButton_Click.")
Logger.WriteLine( Globals.ErrorMessage )
Logger.WriteLine( "ActionTaken: Let user Try Again")
SecondNumberTextBox.Focus()
Return
End If
A "Nested If" statement must be fully encapsulated inside of the block within which it is used as shown above.
We check the value of Globals.CallStatus in the Nested If / End if block.
If CallStatus is still set to Globals.OK the statements inside the nested if block are ignored.
In the MathOperations Divide Function we set Globals.CallStatus to a value other than Globals.OK and put a message in the Globals.ErrorMessage variable if there was a divide by 0 condition.
So, if the Globals.CallStatus is not what we set it to before we executed the call to the Divide Function, "Globals.OK", then the statements inside the nested if End If block get executed.
The IsNumeric( Parm ) is a VB Function to check if the variable inside the parenthsis contains a valid numeric value.
You can find many more VB Statements and KeyWords in either the Local MSDN Library under the Help Menu or in the Online VB.net MSDN Documents.
Begin Optional IntelliSense Example
You already entered the code for the Button's Click Event.
Here is how you might approach typing it in using IntelliSense with WindowEyes.
Note you can get the list under the Edit Menu by expanding the Intellisense item and picking the appropriate option for what you want to see or use the hot keys as described below.
Sometimes this method reads better than using the hot keys.
A WindowEyes script would make Intellisense more comfortable and faster to use.
The following is only for reading, if you elect to actually use it you can copy and paste the above CopiedCode block if this process becomes problematic.
Begin IntelliSense Process
On the blank line after...
Private Sub CalculateButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles CalculateButton.Click
Type...
Dim FirstNumber As Decimal =0
hit enter.
Type...
Dim SecondNumber As Decimal = 0
hit enter.
Type...
Dim Answer As Decimal = 0
hit enter.
Type...
' Test For Valid Input Values
hit enter.
Type...
If Not IsNumeric( FirstNumberTextBox.
Then hit ctrl+j or ctrl+SpaceBar for Intellisense.
cursor to the text property and hit enter.
The statement now looks like...
If Not IsNumeric(FirstNumberTextBox.Text
Finish typing it so it looks like...
If Not IsNumeric( FirstNumberTextBox.Text) Then
hit enter.
If you cursor down a couple of lines you will see that the IDE has added the closing "End If" statement for this "If Statement.
Place your cursor on the blank line between the opening "IF Statement" and the closing "End If" statement.
Type...
MessageBox.
Hit ctrl+j or ctrl+spacebar for Intellisense.
Cursor down to the Show method and hit enter.
The Statement looks like...
MessageBox.Show
Finish typing so it looks like...
MessageBox.Show( "FirstNumberTextBox Is Not Numeric")
hit enter
Type...
FirstNumberTextBox.
Then look under the Edit Menu, expand IntelliSense and hit enter on Members or,
Hit ctrl+SpaceBar or ctrl+j - whichever option reads the best for you.
In the IntelliSense List Cursor to the Focus Method and hit enter.
Finish typing so it looks like...
FirstNumberTextBox.Focus()
Type...
Return
Hit enter
Type...
Else
Hit Enter
Type...
FirstNumber = CDec( FirstNumberTextBox.Text )
Cursor down and the next line is the closing "End If" statement.
Hit enter after the End If statement to add a blank line.
Type...
If Not IsNumeric( SecondNumberTextBox.Text ) Then
Hit Enter
Type...
MessageBox.Show( "SecondNumberTextBox is not numeric" )
Hit Enter
Type...
SecondNumberTextBox.
Bring up Intellisense either under the Edit Menu clicking the Members item or using,
ctrl+SpaceBar or ctrl+j.
Cursor to the focus method hit enter on it.
Finish typing the statement to look like...
SecondNumberTextBox.Focus()
hit enter.
Type...
Return
hit enter.
Type...
Else
hit enter.
Type...
SecondNumber = CDec( SecondNumberTextBox.Text )
Cursor down to read the closing "End If" statement.
End If
hit enter to add a new blank line.
Type the following lines hitting enter after each line...
' Process The Request
' Instantiate a MathOperations Class Object.
Dim OperationsObject As New MathOperations()
Hit enter
Type...
If OperationListBox.
Bring up Intellisense either under the Edit Menu clicking the Members item or using,
ctrl+SpaceBar or ctrl+j.
Cursor to and hit enter on
SelectedItem
Continue typing the statement to look like...
If OperationListBox.SelectedItem = "Add" Then
Hit enter
Type...
Answer = _
hit enter
Type...
OperationsObject.
Bring up Intellisense either under the Edit Menu clicking the Members item or using,
ctrl+SpaceBar or ctrl+j.
Cursor to and hit enter on the Add Function in the Intellisense list.
The statement now looks like...
OperationsObject.Add
Type...
(
Bring up Intellisense either under the Edit Menu clicking the Parameters item or using,
ctrl+Shift+SpaceBar.
You will hear the number and types of parameters required by the Add Function.
Then finish typing the statement to look like...
OperationsObject.Add(FirstNumber, SecondNumber)
That is how IntelliSense works. I use other methods I will describe later to get the same information.
Just type in the rest of the code as follows ...
ElseIf OperationListBox.SelectedItem ="Subtract" Then
Answer = _
OperationsObject.Subtract(FirstNumber, SecondNumber)
ElseIf OperationListBox.SelectedItem = "Multiply" Then
Answer = _
OperationsObject.Multiply(FirstNumber, SecondNumber)
ElseIf OperationListBox.SelectedItem = "Divide" Then
Globals.CallStatus = Globals.OK
Globals.ErrorMessage = ""
Answer = _
OperationsObject.Divide(FirstNumber, SecondNumber)
If Globals.CallStatus <> Globals.OK Then
MessageBox.Show( Globals.ErrorMessage )
Logger.WriteLine( "The Following Error Was Returned to MathForm.CalculateButton_Click.")
Logger.WriteLine( Globals.ErrorMessage )
Logger.WriteLine( "ActionTaken: Let user Try Again")
SecondNumberTextBox.Focus()
Return
End If
Else
MessageBox.Show( "No Operation Found Matching Selected Item - Likely A Typo in CalculateButton ClickEvent")
Return
End If
AnswerTextBox.Text = Answer
AnswerTextBox.Focus()
End Sub
End IntelliSense Process
Hit Alt+w, l to close all open windows and save your
work.
Note- One technique I use is to jump to where variables are declared, where Functions or subs are declared or other objects I am interested in finding out about instead of using IntelliSense.
The Hot keys to do this are...
In VB Code Editor, Just press F12 to go to variable or object declaration
And press Ctrl+- to return back to the piece of code where you were earlier.
EndIntelliSense Example
Step05 Load The ListBox Using MathForm's Load Event
Our OperationList ListBox is on the Form but it has nothing in it. There are several ways to load a List Control like a ListBox but we will load it whenever the Form is being loaded for display.
MathForm is an Object and it has Events.
One of the Events is called the Load Event.
This event is executed every time the form is loaded for display.
Any code put into this event will be executed before the form is displayed on the screen.
When we were editing the Properties for MathForm we added a Subroutine to the MathForm Class that will get executed whenever MathForm is displayed.
Modify The MathForm Load Event Subroutine;
Place cursor on MathForm.vb and hit f7 or,
Right Click On MathForm.vb and pick "View Code"
The Code Editor comes up.
Cursor down to the MathForm_Load Sub opening Statement.
On the blank line after the opening Sub's tag and before end sub add the following lines so it looks like...
BeginCopiedCode:
Private Sub MathForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
Logger.Clear()
OperationListBox.Items.Add( "Add" )
OperationListBox.Items.Add( "Subtract" )
OperationListBox.Items.Add( "Multiply" )
OperationListBox.Items.Add( "Divide" )
OperationListBox.SetSelected(0, True)
End Sub
EndCopiedCode:
Then hit Ctrl+F4 to close the Code Editor and save your work.
Notice, The Logger.Clear will clear our WBLog.txt file when we start the project and MathForm is first loaded.This will keep the text file from building up allot of text from prior runs.
In the above statements we have the OperatorListBox as the object.
Items is a property of the OperationListBox Object and has it's own methods.
It holds a collection of objects to be displayed in the list.
The Add Method of the Items Property adds the string literals as selectable items in OperationListBox.
The final statement executes the SetSelected method of the OperationList object and the index of 0 is the item selected and set to True.
A List Control like a ListBox or ComboBox uses a 0 based index to index it's entries.
Therefore, when the list is displayed the Add Operation will be selected by default.
Now close all open windows, Alt+w, L and save your work.
End Section Add UI Controls to MathForm
Section Test The Calculator
Hit f5 to run the project.
You should be able to enter a couple of numbers, select any of the Arithmetic operations and click Calculate.
The answer should appear in the Answer box.
Notice it is not formatted very well.
End Section Test The Calculator
End Exercise Creating A Calculator
Exercise Number Formatting
Section Number Formatting Introduction
In most all applications it is necessary to format things like numbers and dates to display in a predictable manner.
This is called "String Formatting".
There are 3 ways to format objects to be printed or displayed...
The Format( SomeString ) Function, old school;
The SomeString.Format() Method;
and,
Using the ToString() method associated with various objects.
To keep it simple we will use the ToString() Method in this Tutorial, as we have been doing, and leave the String.Format Method for another day.
We will Create a Sub called DisplayFormatting() in MathOperations Class to demonstrate some of the Formatting Codes.
It will have one Decimal Variable and one Integer Variable called IntVar and DecVar.
We will use Logger to display results of using some of the Formatting Codes against these variables.
We will add a button control to execute this sub to the MathForm.
Feel free to change the numbers in the variables or the Formatting Strings to experiment.
End SectionNumber Formatting Introduction
Section Add A DisplayFormatting() Sub to The MathOperations Class File
Hit ctrl+alt+l to open Solution Explorer.
Cursor to the MathOperations.vb Class file.
Hit f7 to open the VB Code Editer.
On a blank line just before the "End Class" KeyWord statement type in the following sub...
BeginCopiedCode:
Public Sub DisplayFormatting()
Dim IntVar As Integer = 1234678
Dim DecVar As Decimal = 12345.678
Logger.WriteLine( "Some Standard Codes")
Logger.WriteLine( "DecVar is: " & DecVar )
Logger.WriteLine( DecVar.ToString("C2") & " using C2")
Logger.WriteLine( DecVar.ToString("E3") & " using E3")
Logger.WriteLine( DecVar.ToString("N") & " using N")
Logger.WriteLine( "IntVar is: " & IntVar)
Logger.WriteLine( IntVar.ToString("D2") & " using D2")
Logger.WriteLine( IntVar.ToString("F8") & " using F8")
Logger.WriteLine( IntVar.ToString("N") & " using N")
Logger.WriteLine( IntVar.ToString("X") & " using X")
DecVar = .12345
Logger.WriteLine( "DecVar is: " & DecVar)
Logger.WriteLine( DecVar.ToString("P2") & " using P2")
Logger.WriteLine( "A Couple of Custom Format examples")
DecVar = 1234.567
Logger.WriteLine( "DecVar is: " & DecVar)
Logger.WriteLine( DecVar.ToString("#,###.00") & " using #,###.00")
DecVar = 1.23
Logger.WriteLine( "DecVar is: " & DecVar)
Logger.WriteLine( DecVar.ToString("#,###.00") & " using #,###.00")
Logger.WriteLine( DecVar.ToString("#,##0.00") & " using #,##0.00")
DecVar = .23
Logger.WriteLine( "DecVar is: " & DecVar)
Logger.WriteLine( DecVar.ToString("#,##0.00") & " using #,##0.00")
End Sub
EndCopiedCode:
The above statements will demonstrate some of the codes by formatting the numbers when printed to the Logger.txt file for review.
End Section Add A DisplayFormatting() Sub to The MathOperations Class File
Section Add a FormatsButton to MathForm
Now we will add a button to the MathForm so we can execute the new sub.
Let's just plop that puppy under the AnswerTextBox.
Here are the current specs for AnswerTextBox:
Name: AnswerTextBox
Location: 700, 200+ Label Height
Size: 100, Use Compiler Default
TabIndex: 8
So the specs for the new button:
Name FormatsButton
Location: 700, 250
TabIndex: 9
Text: Run Formatting Test
Now, open MathForm in the Designer (hit enter on MathForm.vb).
Ctrl+Alt+x for the ToolBox DropDown and hit enter on Button.
Hit F4 for Properties.
Set:
Name FormatsButton
Location: 700, 250
TabIndex: 9
Text: Run Formatting Test
Now back tab to the tool bar, right cursor and click the Events button.
Hit enter on the "Click" event.
The Subroutine Wrapper statements for the FormatsButton_Click Event are dropped into the MathForm Class VB Code and you are in the Editor.
Since our DisplayFormatting() sub is inside the MathOperations Class code we need to create an Object we can work with.
Again, we create an object from the Class by "Instantiating" it and then use the Instantiated object just as if it were the class code itself.
We just use the name of the Instantiated object to qualify all the public variables, subs, functions and properties in the MathOperations class.
So put the following code into the new sub so it looks like:
BeginCopiedCode:
Private Sub FormatsButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FormatsButton.Click
Dim oMathOperations as New MathOperations
oMathOperations.DisplayFormatting()
MessageBox.Show( "Formatting Test Complete" )
End Sub
EndCopiedCode:
End Section Add a FormatsButton to MathForm
Section Test The Number Formatting Sub
Hit f5, and click "Run Formatting Test ".
The MessageBox should pop up telling you it is done.
Hit Alt+f4 to close the Test and return to the development IDE.
Navigate to your WBLog.txt file and open it.
The Output should look like:
BeginLog:
Initialized
Some Standard Codes
DecVar is: 12345.678
$12,345.68 using C2
1.235E+004 using E3
12,345.68 using N
IntVar is: 1234678
1234678 using D2
1234678.00000000 using F8
1,234,678.00 using N
12D6F6 using X
DecVar is: 0.12345
12.35 % using P2
A Couple of Custom Format examples
DecVar is: 1234.567
1,234.57 using #,###.00
DecVar is: 1.23
1.23 using #,###.00
1.23 using #,##0.00
DecVar is: 0.23
0.23 using #,##0.00
EndLog:
You can experiment with diferent formatting codes to see how they work.
You can also go back and add one of them to the AnswerTextBox value to be displayed by putting them in the (ToString( N ) method as seen in this sample.
End Section Test The Number Formatting Sub
End Exercise Number Formatting
End Unit3 Build A Simple Calculator
Unit4 Arrays, Looping And Intro To Binding
Section Looping And Intro To Binding Overview
We will be creating a form to hold and manage a list of Friends Names.
We will be using an Array to hold the Names to be worked on.
The names will be loaded from and saved to a Text File for Hard Disc storage.
The names will be displayed in a ListBox control.
We will allow for Adding New Names, Changing a Current Name and Removing Names from the Array before saving it.
We will Bind the ListBox to the Array using a "BindingSource" control.
We will apply changes directly to the array using the Methods and Properties of the Array Class and then tell the BindingSource to ReBind the ListBox to the Array after a change.
Note- We do it this way because the Array is a "Fixed Length" object once defined and this method will work in a cleaner and more understandable manner for this Article.
End Section Looping And Intro To Binding Overview
Begin Arrays Overview
VB Arrays are very similar to arrays in Algebra.
Arrays store data elements and allow us to access their elements by numeric index or subscript.
They can be single or multi dimensional.
However, in Vb.net They are 0 based.
That means that the Index can range from a "LowerBound" of 0 to some "UpperBound".
so an array with 5 elements would have:
A "LowerBound" of 0,
An UpperBound" of 4 and,
The index range of 0 through 4.
Arrays are declared using the "Dim" or "ReDim" KeyWords and specifying the Data Type of elements the array will hold.
The following code demonstrates the creation of an array:
'declaring an array to hold a list of 6 string literals.
Dim sport(5) As String
sport(0) = "Soccer"
sport(1) = "Cricket"
sport(2) = "Rugby"
sport(3) = "Aussie Rules"
sport(4) = "BasketBall"
sport(5) = "Hockey"
You can also declare an array without specifying the number of elements by explicitly providing the values to be loaded into the array as follows:
dim Days() as String = {"SUN","MON","TUE","WED","THU","FRI","SAT"}
To use this method you must provide values for each element when initializing the array.
ReInitializing Arrays:
We can change the size of an array after creating it.
The "ReDim" statement assigns a completely new array object to the specified array variable.
You use the "ReDim" statement to change the maximum number of elements in an array.
If you do not use the "Preserve" KeyWord in the "ReDim" statement all data is lost.
This code ReInitializes the Test array declared above.
Example: All data will be lost
ReDim Sport(25) as String
To preserve existing data when ReInitializing an array then use the "Preserve" keyword.
Example: All data will be kept
ReDim Preserve Sport(25)
Multidimensional Arrays:
There are two kinds of multidimensional arrays supported by the .NET framework:
Rectangular arrays and Jagged arrays.
We will not be dealing with Multi Dimensional Arrays in this article.
The concept is the same as in Algebra.
End Arrays Overview
Begin Looping Overview:
A loop executes a block of code multiple times.
There are 4 types of loops:
The For Loop, the Do Loop, the While Loop and the For Each Loop.
Note- the [ ] means an optional feature.
The For Loop;
For loops enable us to execute a series of expressions multiple numbers of times.
The For loop in VB .NET needs a loop index which counts the number of loop iterations as the loop executes.
The syntax for the For loop looks like this:
For index =start to end [Step 1]
(statements)
[Exit For]
(statements)
Next [index]
Each time in the loop, index is incremented by step and when index equals end, the loop ends.
If you do not code the "Step" Keyword the value +1 is assumed.
Example of a For loop
Dim ndx As Integer
For ndx = 0 To 10 Step 1
If d = 4 Then
Exit Do
End If
MessageBox.Show( "The index is " & d.ToString())
Next ndxd
The above loop would execute 5 times, while ndx was 0 through 4.
When ndx hits 5 the loop would stop and processing would continue with the next statement after the "Next ndx" KeyWord statement.
The While loop;
The While loop keeps executing until the condition against which it tests remain true.
The syntax of while loop looks like this:
While condition
(statements)
End While
Example on While loop
Dim ndx , e As Integer
d = 0
e = 6
While e > 4
e -= 1
d += 1
End While
In the above statement the code would execute increasing d by 1 and decreasing e by 1 on each iteration.
When e = 4 the loop stops and processing continues with the next statement after the "End While" statement.
The Do Loop;
The Do loop can be used to execute a fixed block of statements an indefinite number of times.
The Do loop keeps executing it's statements "while" or "until" the condition is true.
It uses one of 2 KeyWords to determine when to end:
"while" or "until".
The Do loop also supports a "Exit Do" statement.
The syntax of the Do loop:
Do [(while or Until) condition]
(statements)
[Exit Do]
(statements)
Loop
Example for Do loop with "Until" condition
Have a user enter words into a textbox.
Execute some code each time he enters a word.
When he enters "Cool" exit the loop.
Do Until TextBox1.Text = "Cool"
Read user's entry.
Do things you want to do if the user enters anything but "Cool"
Loop
Example of a Do loop with "While" condition
Do while TextBox1.Text = "Cool"
Read User's entry.
Do things you want to do every time the user enters "Cool.
Loop
The loop would continue while the user enters "Cool".
As soon as the user enters anything other than "Cool" into the TextBox1 the loop would end.
The For Each Loop;
The For Each Loop executes once for each item in a collection like an array.
We need to specify an object to use to check against the list as the same type of object that the list holds.
Suppose you have a list of Cars in a String Array called Cars...
You want to search the list for the "Ford" entry and change it to "MyFord".
First you define a String Variable to use to search the String Array.
Dim Car as String
To find the string "Ford" and change it to "MyFord"
For Each Car In Cars
If Car = "Ford" Then
Car = "MyFord"
End If
Next Car
After this was run the value "Ford" in the array would be replaced with the value "MyFord".
End Looping Overview:
Begin Binding Overview
An Overview to DataBinding and links to other related topics can be found in the Microsoft Documentation at theURL:
http://msdn.microsoft.com/en-us/library/c8aebh9k(v=VS.90).aspx
When you have UI Controls like ListBoxes, ComboBoxes, ListViews, TextBoxesand others, you will usually want to populate them with Data from some data source.
The Data Source might be a DataBase, XML Source, a file, an Online Web Service or other source where data is to be pulled from.
The concept of "Binding" refers to the ability to pick a source of your data and then, by specifying a few properties and methods, have much of that code automatically generated.
Binding, via the BindingSource control, also manages keeping the display control, like a ListBox or TextBox, in sync with it's underlying DataSource which could be a Data Table, Array or other internal representation of some data.
At it's simplest you just specify a "DataSource" for a control like a ListBox when you add it to the Designer.
If you specify a control like a ListBox or TextBox you get "One Way DataBinding" using this approach.
The data is read from the underlying Storage object, like a DataSet or Array, and displayed in the UI Control automatically.
This is called "OneWay" binding and is just read only but good for initially loading data from a DataSource.
Suppose you have a file or database.
You might load an array with a list of names pulled from that file.
You could then put the name of the array in the DataSource property of a ListBox and the names would be automatically displayed on the form in the ListBox.
If you wanted to add names, change names or remove names from the ListBox using it's methods the changes would not be reflected in the array.
This means that when you save the array's contents back to the Data Store the changes would not be saved since they would not have been applied to the array but only to the ListBox itself.
To wire up the ListBox and the underlying DataSource, the array in this case, you could either code the changes manually or use 2 way DataBinding.
2 Way DataBinding will keep the underlying DataSource in sync with the contents of bound objects like a ListBox or other UI controls.
We use a MS Control called a "BindingSource" to accomplish this.
The BindingSource control will make sure that a UI Control and it's underlying DataSource like an Array or DataSet are in the same state whether we add, remove, change, sort or otherwise make changes to the elements being displayed.
The BindingSource also manages something called "Currency". Currency is the management of keeping all UI controls bound to the same DataSource in sync with each other as well as the underlying DataSource as you navigate through them on the form.
End Binding Overview
Begin MSDN Binding Summary
As stated above, an Overview to DataBinding and links to other related topics can be found in the Microsoft Documentation at theURL:
http://msdn.microsoft.com/en-us/library/c8aebh9k(v=VS.90).aspx
Data Binding and Windows Forms
In Windows Forms, you can bind to not just traditional data sources, but also to
almost any structure that contains data. You can bind to an array of values that
you calculate at run time, read from a file, or derive from the values of other controls.
In addition, you can bind any property of any control to the data source. In traditional
data binding, you typically bind the display property—for example, the
Text
property of a
TextBox
control—to the data source. With the .NET Framework, you also have the option of
setting other properties through binding as well. You might use binding to perform
the following tasks:
Setting the graphic of an image control.
Setting the background color of one or more controls.
Setting the size of controls.
Essentially, data binding is an automatic way of setting any run-time accessible
property of any control on a form.
Types of Data Binding
Windows Forms can take advantage of two types of data binding: simple binding and
complex binding. Each offers different advantages.
Type of data binding
Description
Simple data binding
The ability of a control to bind to a single data element, such as a value in a column
in a dataset table. This is the type of binding typical for controls such as a
TextBox
control or
Label
control, which are controls that typically only displays a single value. In fact,
any property on a control can be bound to a field in a database. There is extensive
support for this feature in Visual Studio.
For more information, see
Interfaces Related to Data Binding
and
How to: Navigate Data in Windows Forms
and
How to: Create a Simple-Bound Control on a Windows Form
and
...
Complex data binding
The ability of a control to bind to more than one data element, typically more than
one record in a database. Complex binding is also called list-based binding. Examples
of controls that support complex binding are the
DataGridView
,
ListBox
, and
ComboBox
controls. For an example of complex data binding, see
How to: Bind a Windows Forms ComboBox or ListBox Control to Data
.
BindingSource Component
To simplify data binding, Windows Forms enables you to bind a data source to the
BindingSource
component and then bind controls to the
BindingSource
. You can use the
BindingSource
in simple or complex binding scenarios. In either case, the
BindingSource
acts as an intermediary between the data source and bound controls providing change
notification currency management and other services.
Common Scenarios That Employ Data Binding
Nearly every commercial application uses information read from data sources of one
type or another, usually through data binding. The following list shows a few of
the most common scenarios that utilize data binding as the method of data presentation
and manipulation.
Scenario
Description
Reporting
Reports provide a flexible way for you to display and summarize your data in a printed
document. It is very common to create a report that prints selected contents of a
data source either to the screen or to a printer. Common reports include lists, invoices,
and summaries. Items are usually formatted into columns of lists, with sub-items
organized under each list item, but you should choose the layout that best suits
the data.
Data entry
A common way to enter large amounts of related data or to prompt users for information
is through a data entry form. Users can enter information or select choices using
text boxes, option buttons, drop-down lists, and check boxes. Information is then
submitted and stored in a database, whose structure is based on the information entered.
Master/detail relationship
A master/detail application is one format for looking at related data. Specifically,
there are two tables of data with a relation connecting them—in the classic business
example, a "Customers" table and an "Orders" table with a relationship between them
linking customers and their respective orders. For more information about creating
a master/detail application with two Windows Forms
DataGridView
controls, see
How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls
Lookup Table
Another common data presentation/manipulation scenario is the table lookup. Often,
as part of a larger data display, a
ComboBox
control is used to display and manipulate data. The key is that the data displayed
in the
ComboBox
control is different than the data written to the database. For example, if you
have a
ComboBox
control displaying the items available from a grocery store, you would probably
like to see the names of the products (bread, milk, eggs). However, to ease information
retrieval within the database and for database normalization, you would probably
store the information for the specific items of a given order as item numbers (#501,
#603, and so on). Thus, there is an implicit connection between the "friendly name"
of the grocery item in the
ComboBox
control on your form and the related item number that is present in an order. This
is the essence of a table lookup.
For more information, see
How to: Create a Lookup Table with the Windows Forms BindingSource Component
and
...
See Also
Tasks
How to: Bind the Windows Forms DataGrid Control to a Data Source
Reference
Binding
Other Resources
Windows Forms Data Binding
BindingSource Component
End MSDN Binding Summary
Exercise Build A FriendsForm
Section FriendsForm Introduction
We will use a simple ComboBox to display a list of Friend Names held in a WBFriendNames.txt file.
We will use a TextBox for adding new names or changing names.
We will add 3 buttons to
1) Add a name to the list;
2) Remove a name;
3) Change a name.
We will use one way binding to display the contents of the WBFriendNames.txt file after loading it into an Array.
We could use the methods of the ListBox to do this but this is an intro to arrays and binding so we will apply the changes to the Array and ReBind after each change to reflect the change in the ComboBox and TextBox.
End Section FriendsForm Introduction
Section The WBFriendNames.txt File
Step01 Add WBFriendNamesPath To Globals
We want to keep our WBFriendNames.txt file someplace so add a Variable called WBFriendNamesPath to the Globals.vb file as follows:
Open Solution Explorer, (ctrl+alt+l).
Cursor to Globals.vb and hit F7.
Add the following statement after the statement that declares the WBLogPath so the file looks like...
BeginCopiedCode:
Public Class Globals
Public Shared CallStatus As Integer = 0
Public Shared ErrorMessage As String = ""
Public Shared Found As Boolean = False
Public Shared WBLogPath As String = _
"C:\WinformBasics\WBLog.txt"
Public Shared WBFriendNamesPath As String = _
"c:\WBFriendNames.txt"
' Constants
Public Const OK As Integer = 1
Public Const CallError As Integer = -1
End Class
EndCopiedCode:
End Section The WBFriendNames.txt File
Section Design The FriendsForm Layout
We want a TextBox, ListBox and 3 buttons on the form.
We will just put the TextBox over the ListBox in the upper left of the window.
The 3 buttons will be aligned vertically over to the right of the window.
Here are some settings to do this...
Label Control:
Name: CurrentNameLabel
Location: 50, 100
Text: CurrentName
TabIndex: 1
TextBox:
Name: CurrentNameTextBox
BackColor: black
ForeColor: white
Location: 50, 100 + label Height
Size: 400, use default height.
TabIndex: 2
ComboBox:
Name: NamesComboBox
BackColor: black
ForeColor: white
Location: 50, 150
Size 400, 400
TabIndex: 3
Buttons:
Name: AddButton
Location: 500, 100
Text: AddName
TabIndex: 4
Name: ChangeButton
Location: 150
Text: ChangeName
TabIndex: 5
Name: RemoveButton
Location: 500, 200
Text: Remove
TabIndex: 6
End Section Design The FriendsForm Layout
Section Add The Form And Set As Start Form
Open Solution Explorer (ctrl+alt+l)
Cursor to UserForms.
Hit New windows form under the Project Menu.
Name the Form FriendsForm.vb, tab and hit the Add Button.
If you are in the Designer hit F4 to bring up the Properties Window otherwise
cursor to NamesForm.vb and hit shift+f7.
Then F4 to get into the Properties Window.
Set...
BackColor: Navy
Cursor to the Font Property and expand it,
size 12
Font Measurement: Pixel
Cursor to the ForeColor property.
Set it to white
cursor to and set
Size: 1000, 700
StartPosition: Center Screen
BackTab to the ToolBar and right cursor to Events Button, click it and hit enter on the Load event.
You are placed in the VB Code Editor.
It looks like...
BeginCopiedCode:
Public Class FriendsForm
Private Sub FriendsForm_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
EndCopiedCode:
Hit alt+w, l to close all open windows and save your work.
End Section Add The Form And Set As Start Form
Section Add UI Controls
Hit enter on FriendsForm.vb, or hit shift+f7 while on it, to open the Designer.
Hit ctrl+alt+x for the ToolBox.
Drop a Label control on the Designer and hit F4.
Set...
Name: CurrentNameLable
Location: 50, 100
TabIndex: 1
Text: Current Name
Note- make note of the Height setting of the Size property, mine is 15.
Hit f4 to close the Properties window.
Hit ctrl+alt+x and drop a TextBox on the Designer.
Set...
Name CurrentNameTextBox
BackColor: black
ForeColor: White
Location: 50, 115 (Note- that is 100 plus the height of my currentNameLabel)
Size: 400, (Leave Default Height)
TabIndex: 2
Hit ctrl+f4 to close the Properties Window and return to the Designer.
Hit ctrl+alt+x for the ToolBox.
Drop a ListBox on the Designer.
Set...
Name: NamesListBox
BackColor: black
ForeColor: white
Location: 50, 150
Size: 400, 400
TabIndex: 3
Hit F4 to close Properties Window and return to Designer.
Hit ctrl+alt+x for the ToolBox.
Drop a Button on the Designer.
Copy It to the ClipBoard and Paste 2 more buttons on the Designer.
Tab to Button1 and set...
Name: AddButton
Location: 500, 100
TabIndex: 4
Text: Add Name
BackTab to the ToolBar, cursor and click Events, then click the Click Event.
In the Sub add the line,
MessageBox.Show( "You Clicked Add")
It should look like...
BeginCopiedCode:
Private Sub AddButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
MessageBox.Show( "You Clicked Add" )
End Sub
EndCopiedCode:
Hit shift+f7 to switch to the Designer.
Tab to Button2 and hit f4.
If you come up in the Events list back tab to the tool bar and right cursor to Properties button and click it.
Tab to get into the Properties List.
Set...
Name: DeleteButton
Location: 500, 150
TabIndex: 5
Text: Delete
BackTab to the ToolBar, cursor and click Events, then click the Click Event.
In the Sub add the line,
MessageBox.Show( "You Clicked Delete")
BeginCopiedCode:
Private Sub DeleteButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteButton.Click
MessageBox.Show( "You Clicked Delete")
End Sub
EndCopiedCode:
Hit shift+f7 to switch to the Designer.
Tab to Button3 and hit f4.
BackTab to the ToolBar and right cursor to and click the Properties Button.
Tab to the Properties List and set...
Name: ChangeButton
Location: 500, 200
TabIndex: 6
Text: Change
BackTab to the ToolBar, cursor and click Events, then click the Click Event.
In the Sub add the line,
MessageBox.Show( "You Clicked Change")
BeginCopiedCode:
Private Sub ChangeButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangeButton.Click
MessageBox.Show( "You Clicked Change")
End Sub
EndCopiedCode:
Hit alt+w, l to close all open windows and save the work.
End Section Add UI Controls
Section Test The UI
Now, hit F5 to run the form.
You should be able to tab around and hear your controls read properly.
If you click a button the MessageBox should pop up telling you which button was clicked.
Hit Alt+f5 to close the Test Environment.
Hit Alt+w, l to close any remaining open windows and save your work if asked.
End Section Test The UI
Section Wire Up The Form
Step01 Initialize the LoadEvent
Hit ctrl+alt+l to open Solution Explorer.
Cursor to FriendsForm.vb and hit f7 to open the VB Code Editor.
We need to add an Imports Statement to reference the IO Namespace.
We need 2 Class Level definitions.
We want an array and a BindingSource control we can use with all the subs and functions we will add to this class.
We will add a Class Level Array named NamesArray and a Class level BindingSource control named NamesBindingSource. control as follows...
BeginCopiedCode:
Imports System.IO
Public Class FriendsForm
Dim NamesArray( 100 ) As String
Dim NamesBindingSource As New BindingSource()
Private Sub FriendsForm_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If File.Exists( Globals.WBFriendNamesPath ) Then
NamesArray = File.ReadAllLines( Globals.WBFriendNamesPath )
End If
NamesBindingSource.DataSource = NamesArray
NamesListBox.DataSource = BindingSource1
End Sub
EndCopiedCode:
This code will read the contents of the WBFriendNames.txt file into the NamesArray.
If the file does not exist The NamesListBox will appear empty until there are records to display.
Then we bind the NamesBindingSource to the NamesArray and the ListBox to the BindingSource by specifying their names in the DataSource properties of the BindingSource and ListBox controls.
Step02 Wire Up The AddButton
Cursor to the blank line between the AddButton Click Event Sub's opening statement and End Sub closing statement.
Modify the code as follows...
BeginCopiedCode:
Private Sub AddButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
Globals.Found = False
For ndx As Integer = 0 To NamesArray.GetUpperBound(0)
If NamesArray( ndx ) = "" Then
NamesArray( ndx ) = CurrentNameTextBox.Text
Globals.Found = True
NamesBindingSource.ResetBindings( false )
NamesBindingSource.Position = ndx
CurrentNameTextBox.Text = ""
Exit For
End If
Next ndx
If Globals.Found = False Then
MessageBox.Show( "NamesArray is full, Must delete a name before you can add another name.")
End If
End Sub
EndCopiedCode:
Hit Alt+w, l to close the windows and save the work.
Hit F5 to run the form.
Enter a name in the CurrentName TextBox and click the AddButton.
The new name should be added to the NamesListBox.
Repeat this a couple of times to make sure it is working correctly.
Hit Alt+F4 to close the Test Environment.
Step03 Wire Up The DeleteButton
Hit F7 with the cursor on FriendsForm.vb to open the VB Code Editor.
Cursor to the blank line between the DeleteButton Click Event sub opening and closing statements.
Modify the code to look like...
BeginCopiedCode:
Private Sub DeleteButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteButton.Click
NamesArray.SetValue( "Removed", NamesBindingSource.Position )
NamesBindingSource.ResetBindings( false )
End Sub
EndCopiedCode:
In the above 2 statements we
used the SetValue method of the Array Class to set the value of the selected name to a literal value of "Removed".
Then we ReBound the NamesListBox and the NamesArray using the BindingSource's ResetBindings method.
Note how we could not just delete one of the items and have all the other items automatically ReIndexed within the Array. That is because the Array Object is a Fixed Array and once a value is placed into a slot that items relative position can not be changed without ReBuilding the Array or manually ReLoading the elements into new slots.
The control more flexible to use in this case would be the ArrayList object which is a Collection rather than a true array.
Since this unit is about arrays we are using an array object for the demonstration.
Step04 Wire Up The ChangeButton
Hit F7 with the cursor on FriendsForm.vb to open the VB Code Editor.
Cursor to the blank line between the ChangeButton Click Event sub opening and closing statements.
Modify the code to look like...
BeginCopiedCode:
Private Sub DeleteButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteButton.Click
NamesArray.SetValue( "Removed", NamesBindingSource.Position )
NamesBindingSource.ResetBindings( false )
CurrentNameTextBox.Text = ""
End Sub
EndCopiedCode:
In the above 2 statements we
used the SetValue method of the Array Class to change the value of the Selected Item in the NamesListBox to the Name entered in the CurrentNameTextBox.Text property.
Then we ReBound the NamesListBox and the NamesArray using the BindingSource's ResetBindings method.
End Section Wire Up The Form
Section Save Changes To WBFriendNames.txt
We will add the "FormClosing" Event Sub to FriendsForm's VB Code File.
We will use the "DialogResult" value of a MessageBox to determine if the user wants to save the changes.
If they do we will clear the file and then write one line for each name in the NamesArray.
This will automatically create the file if it does not exist.
Cursor to FriendsForm.vb and hit enter.
Hit f4 to open the Properties Window.
Verify that "FriendsForm" is loaded in the Text Property.
BackTab to the ToolBar, right cursor to and click the EventsButton.
Hit enter on the FormClosing Event.
Modify the Code to look like...
BeginCopiedCode:
Private Sub FriendsForm_FormClosing( ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
' This sub will...
' Verify the user wants to save any changes.
' Backup The original WBFriendNames.txt file.
' Loop through NamesArray writing one line per name to the New WBFriendNames.txt file
' If any error occurs log a message, restore the original file and return, exit Form Processing.
' set up A "Yes/No" MessageBox
Dim message As String = _
"Do you want to save the changes?"
Dim caption As String = "Form Closing"
Dim result = MessageBox.Show(message, caption, _
MessageBoxButtons.YesNo, _
MessageBoxIcon.Question)
If (result = DialogResult.No) Then
Return
End If
' Create A Backup of the WBFriendNames.txt file
Dim TempBackUpFile As String = Globals.WBFriendNamesPath
TempBackupFile = TempBackupFile.Replace( ".txt", ".bak")
Try
File.Copy(Globals.WBFriendNamesPath, TempBackupFile, True )
File.Delete( Globals.WBFriendNamesPath )
Catch TryMessage As Exception
MessageBox.Show( "Error backing up WBFriendNames File. File Not changed. Check Log For details.")
Logger.WriteLine( "Error backing up WBFriendNames in FriendsForm, FormClosing Sub.")
Logger.WriteLine( "WBFriendNames Not Modified.")
Logger.WriteLine( TryMessage.ToString())
Return
End Try
' Loop Through NamesArray Slots
For ndx As Integer = 0 To NamesArray.GetUpperBound(0)
' Do not save empty slots to the file
If NamesArray(ndx) = "" Then
GoTo NextIndexTag
End if
' Write a line to the file
Try
File.AppendAllText( Globals.WBFriendNamesPath, NamesArray( ndx ) )
File.AppendAllText( Globals.WBFriendNamesPath, vbCrLf )
Catch TryMessage As Exception
MessageBox.Show( "Exception Writing to WBFriendNames. Attempting to Restore the file. Check Log for details.")
Logger.WriteLine( "Error inFriendsForm, FormClosing sub.")
Logger.WriteLine( "Exception Writing to WBFriendNames." )
Logger.WriteLine( "Attempting to restore the original file.")
Logger.WriteLine( TryMessage.ToString())
File.Copy( TempBackupFile, Globals.WBFriendNamesPath, True )
Return
End Try
NextIndexTag:
Next ndx
' At this point the file should be created and loaded so delete the backup file
File.Delete( TempBackupFile )
End Sub
EndCopiedCode:
End Section Save Changes To WBFriendNames.txt
Note- We used the "Replace" method of the String Class.
We will dig into the String Class in the next unit.
End Unit4 Arrays, Looping And Intro To Binding
Unit5 Working With Strings
Section Working With Strings Overview
In this unit i just use a single button and modify the code in it's click event to demonstrate each exercise.
If you want to you could drop one button for each Exercise on the form so you can save the code.
You would...
Drop a Button on the form for an exercise, set it's properties, add it's click event and place the Exercise code inside it.
Then you just click that button to run that exercise.
End Section Working With Strings Overview
Section Concepts
Begin Concept String Literals
A String is a group of letters, numbers and other characters that we can describe as being text.
A String Literal is enclosed in quote marks.
"This is a string"
"I can count 1, 2, 3!, see."
You can use a String Literal in Functions and Subroutines or assign it to variables.
The MessageBox function is a BuiltIn function of Vb used to display something on the screen.
You could display a String Literal on the screen as follows...
MessageBox.Show( "Hello World" ).
When the MessageBox statement was executed the words "Hello World" would appear on the screen along with an OK button you would click to close the Message.
End Concept String Literals
Begin Concept String Variables
A String Variable is a variable that holds a string of text.
You declare it and then you can save a string literal in it.
you can use that saved string by just using the name of the String Variable.
For Example...
Dim MyString as String
MyString = "Hello World"
The "Dim" statement declares a String Variable named MyString.
We then assigned the value "Hello World" to the variable.
In code we could use the string variable as follows,
MessageBox.Show( MyString )
When this statement is executed the words "Hello World" would be displayed in the MessageBox.
It is the same as if you had put the string literal in the statement.
MessageBox.Show( "Hello World" ).
End Concept String Variables
End Section Concepts
Section Create StringsForm - Overview
We want to have another form where we can demonstrate some String Functions.
End Section Create StringsForm - Overview
Section Design The Form Layout
We are going to put 2 single line textboxes in the upper Left Quadrant of the form, a big MultiLine TextBox in the UpperRight Quadrant extending into the Lower Quadrant and a Button in the UpperLeft Quadrant under the First 2 SingleLine TextBoxes.
Also, we will add labels to the boxes that will get read when we tab to one of them.
We will name them...
FirstSingleLineLabel, SecondSingleLineLabel and MultiLineLabel.
FirstSingleLineBox, SecondSingleLineBox and MultiLineBox.
We won't need a label for the Button.
We will put the labels above the boxes so they are touching the box.
This looks adiquit for our purposes and it works well to make a label read with a screen reader, at least with Windoweyes.
Here is the Plan...
Here are some roughed out values that will work.
Name: FirstSingleLineLabel
Location: 50, 100
TabIndex: 1
Text: First String
Note- The Size will automatically be set based on font and text length.
Name: SecondSingleLineLabel
Location: 50, 200
TabIndex: 3
Text: Second String
Name: MultiLineLabel
Location: 500, 100
TabIndex: 5
Text: MultiLine Text
Name: FirstSingleLineBox
Location: 50, (100 + Height of label control)
Size: 400, (Leave Default Height)
TabIndex: 2
Name: SecondSingleLineBox
Location: 50, (200 + height of label)
Size: 400, (Leave Default Height)
TabIndex: 4
Name: MultiLineBox
Location: 500, (100 + Label Height)
MultiLine: True
Size: 400, 500
TabIndex: 6
Name: TestButton
Location: 50, 300
Text: Run Test
Size: 100, (Leave Default Height Setting)
TabIndex: 7
Note- we will get the Height from the Properties Window for the Label controls when we add the controls.
End Section Design The Form Layout
Section Add StringsForm, Set Properties And Set As Startup Form
Step01 Add StringsForm, Set Properties And Add Load Event
Open Vb.net and click on WinformBasics in the ProjectList to open it.
Close All windows - (Alt+w, l).
Hit Ctrl+Alt+l to open Solution Explorer.
Cursor To the UserForms Folder.
Hit Alt and Under the "Project" Menu click "Add Windows Form".
Tab to the Name EditBox and enter StringsForm.vb then tab and click the Add Button.
If you are not placed in the Designer Hit Enter on StringsForm.vb to open the Forms Designer.
Hit F4 to open the Properties Window.
Go to the top of page and start cursoring down the list and set...
Backcolor: Navy
Expand the Font Branch,
Cursor toSize, Tab and set it to 12.
Back tab to the list and,
Cursor to Unit, tab past the edit box to the Browse Button and select Pixel from the ListView list of Font measurement unit types by hitting enter on it.
The Font Property Now Reads,
Microsoft Sans Serif, 12px
Back in the PropertiesList, Cursor down to Forecolor and either select or type in white.
Cursor Down to size and set it to 1000, 700 in the EditBox.
Continue cursorring down to Start Position and tab to the Browse button and click it.
Select Center Screen and hit enter.
You are returned to the Properties Window list of properties for the form.
Back Tab to the Tool Bar and right cursor to the Events button.
Click it and hit enter on the Load event.
Add the following line of code on the blank line between the Sub opening and closing tags.
Logger.Clear()
The code should look like...
BeginCopiedCode:
Public Class StringsForm
Private Sub StringsForm_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Logger.Clear()
End Sub
End Class
EndCopiedCode:
Hit Alt+w, l to close all open windows and save the work.
The call to Logger.Clear()will clear the WBLog.txt file when StringsForm is loaded for testing.
Step02 Set "StringsForm" As the Project Default Form
Now, Under the Project Menu hit enter on the WinformBasics Properties item.
Tab and open the Start Form ComboBox.
Cursor down and click StringsForm, tab and hit F4 to close the Project Properties Dialog.
Hit F5 to run the page and verify StringsForm is in the TitleBar.
If not ReTry setting it as the Start Page.
End Section Add StringsForm, Set Properties And Set As Startup Form
Section Add UI Controls To StringsForm
Step01Add The Labels
Hit Enter on StringsForm.vb to open the Designer again.
Open the ToolBox ( Ctrl+Alt+x)
There are several expandable / Collapsable categories of controls you can look at by hitting left cursor or right cursor to expand or collapse a category.
A long list of many of the objects is the "All Windows Forms"
Under it is "Common Controls"
Under that is "Containers"
Under that "Menus And ToolBars"
Then "Data"
Then "Components"
Then "Printing"
Then "Dialogs"
Then "WPF Interoperability"
then "Visual Basic PowerPacks"
Finally "General" just an empty branch.
Expand either "AllWindows Forms" or "Common Controls"
Common Controls is faster to cursor up and down, less entries to wade through.
Cursor to the Label item in the list and hit enter on it.
A Label Control called Label1 is added to the Designer.
Tab to and copy Label1 to the ClipBoard ( ctrl+c).
Hit ctrl+p twice to add 2 more labels to the Designer.
They will be named Label2 and Label3.
Tab back to Label1 and hit F4.
In the Properties Window...
The BackColorFont and ForeColor are set to our StringsForm defaults already.
Set...
Name: FirstSingleLineLabel
Location: 50, 100
TabIndex: 1
Text: First String
Note- The Size will automatically be set based on font and text length.
Hit ctrl+f4 to return to Designer.
Tab to Label2 and set...
Name: SecondSingleLineLabel
Location: 50, 200
TabIndex: 3
Text: Second String
Make a note of the Size property for positioning the TextBoxes.
Mine is,
84, 15
Hit ctrl+f4 to return to Designer.
Tab to Label3 and set...
Name: MultiLineLabel
Location: 500, 100
TabIndex: 5
Text: MultiLine Text
Make a note of the Size Height property for positioning the TextBoxes.
Mine is, 15
Hit ctrl+f4 to return to Designer.
Step02 Add The TextBoxes
Still in the Designer,
Open the ToolBox and Drop A TextBox Control on the Designer.
Tab to and copy it to the ClipBoard, it is named TextBox1 by default.
Hit ctrl+p twice to add 2 more text boxes to the Designer.
They will be named TextBox2 and TextBox3.
Tab to TextBox1, hit F4 and set the Properties...
Name: FirstSingleLineBox
BackColor: black
ForeColor: White
Location: 50, 115
Size: 400, (Leave Default Height)
TabIndex: 2
Hit Ctrl+F4 to return to the Designer.
Tab to TextBox2 hit F4 and set the Properties...
Name: SecondSingleLineBox
Location: 50, 215
Size: 400, (Leave Default Height)
TabIndex: 4
Hit Ctrl+F4 to return to the Designer.
Tab to TextBox3, hit F4 and set the Properties...
Name: MultiLineBox
Location: 500, 115
MultiLine: True
Size: 400, 500
TabIndex: 6
Hit Ctrl+F4 to return to the Designer.
Step03 Add And Wire Up The Button's Click Event
Drop a Button Control On the Designer.
Hit F4 and set...
Name: TestButton
Location: 50, 300
Text: Run Test
Size: 100, (Leave Default Height Setting)
TabIndex: 7
Now, BackTab to the ToolBar, cursor to the Events Button and click it.
Hit enter on the click Event.
You are placed in the VB Code Editor for this event.
Modify the code to look like...
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
MessageBox.Show( "You Clicked me!")
End Sub
EndCopiedCode:
Close all open Windows ( Alt+w, l) and save your work.
Note the following "Access Modifier":
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
Note the use of the "Private" Access Modifier.
The "Private" Scope of this Sub means it can only be used, inside this Class.
The Compiler adds code to this class behind the scenes that call this Subroutine when the button is clicked.
This makes sense since nobody should click this button unless they are working on this form.
Hit F4 or alt+w, l to close the windows and save your work.
Hit F5 to run the project.
You should be able to tab around the window and the tab stops should be on...
First String, Second String, MultiLine Text and Run Test.
Click the Run Test button and the MessageBox should pop up.
Click ok to close it.
Hit Alt+f4 to close the Test Form.
If there is an error in the reading order check your TabIndex values and your Location settings.
Once it is reading properly continue.
End Section Add UI Controls To StringsForm
Section Notes On Exercise Procedures
When testing, Do not hit the enter key nor the tab key while in the MultiLineBox.
We have not set it up to handle Enter nor Tab so they will do nothing.
Just type your text in one long string with no enter or tabs.
The text will automatically wrap when you get to the end of a line.
End Section Notes On Exercise Procedures
Exercise Using The String Length Property
In this exercise we will...
Create a String Variable named TempString.
Save the text we type into MultiLineBox in the String Variable.
Display the length of the text held in TempString.
Step01;
Clear your workspace ( alt+w, l).
Hit Ctrl+Alt+L for Solution Explorer.
Cursor to StringsForm.vb and hit F7 or,
Right click StringsForm.vb and select "View Code".
Modify the code in the TestButton's Click Event Subroutine to look like...
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
Dim TempString As String = MultiLineBox.Text
FirstSingleLineBox.Text = TempString.Length()
End Sub
EndCopiedCode:
Hit ctrl+f4 to save the change.
Hit F5 to run the test.
Type some text into MultiLineBox and click the Run Test button.
The number of characters, including spaces, should be displayed in FirstSingleLineBox.
End Exercise Using The String Length Property
Exercise Using The Replace Method
In this exercise we will...
Type some text in MultiLineBox.
In FirstSingleLineBox Type some text to be replaced, something in MultiLineBox.
In SecondSingleLineBox Type something to replace it with.
Copy the text from MultiLineBox into TempString.
Perform the Replacement.
Display the modified text back into MultiLineBox.
Step01;
Clear your workspace ( alt+w, l).
Hit Ctrl+Alt+L for Solution Explorer.
Right click StringsForm.vb and select "View Code".
Modify the code in the TestButton's Click Event Subroutine to look like...
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
Dim TempString As String = ""
TempString = MultiLineBox.Text
TempString = TempString.Replace( FirstSingleLineBox.Text, SecondSingleLineBox.Text)
MultiLineBox.Text = TempString
MultiLineBox.Focus()
End Sub
EndCopiedCode:
Hit ctrl+f4.
Hit F5 to run the test.
If the text you typed into FirstSingleLineBox was found in the MultiLineBox it will have been replaced with what you typed into SecondSingleLineBox.
If not, no change will have occured.
End Exercise Using The Replace Method
Exercise Using The IndexOf Method
In the above example nothing happened if the value you entered in FirstSingleLineBox was not in the MultiLineBox.
We can find the first occurance of a single character or a ssubstring using the IndexOf method of the String Class.
If a match is found the value of this method will be the position of where the character is located or the position of the first character of the matching string.
If the Character or SubString is not found the method will return -1.
In this exercise we will...
Create a Integer variable named Position.
Save the text we type into MultiLineBox in a String Variable.
Check to see if the text we type into FirstSingleLineBox is in the string variable.
If the Text is found we will replace it with text we type into SecondSingleLineBox and ReDisplay it in MultiLineBox.
If the search string is not found,
we will display a message that the text was not found in a MessageBox,
set focus to FirstSingleLineBox and Exit the Subroutine.
Clear your workspace ( alt+w, l).
Hit Ctrl+Alt+L for Solution Explorer.
Right click StringsForm.vb and select "View Code".
Modify the code in the TestButton's Click Event Subroutine to look like...
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
Dim TempString As String = ""
Dim StartPosition As Integer = -1
TempString = MultiLineBox.Text
StartPosition = TempString.IndexOf( FirstSingleLineBox.text )
If StartPosition < 0 Then
MessageBox.Show( "String Was Not Found")
FirstSingleLineBox.Focus()
Return
Else
TempString = TempString.Replace( FirstSingleLineBox.Text, SecondSingleLineBox.Text)
End If
MultiLineBox.Text = TempString
MultiLineBox.Focus()
End Sub
EndCopiedCode:
Hit ctrl+f4.
Hit F5 to run the test.
If the text you typed into FirstSingleLineBox was found in the MultiLineBox it will have been replaced with what you typed into SecondSingleLineBox.
If not,
You will get a message and no change will have occured.
End Exercise Using The IndexOf Method
Exercise String Concatenation
In Visual Basic the string Concatenation character is a "&" symbol.
This symbol says to append a second string to a first string.
In this exercise we will...
Type a string into FirstSingleLineBox and SecondSingleLineBox.
Concatenate them and display the result in MultiLineBox.
Clear your workspace ( alt+w, l).
Hit Ctrl+Alt+L for Solution Explorer.
Right click StringsForm.vb and select "View Code".
Modify the code in the TestButton's Click Event Subroutine to look like...
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
Dim TempString As String = ""
TempString = FirstSingleLineBox.Text & SecondSingleLineBox.Text
MultiLineBox.Text = TempString
MultiLineBox.Focus()
End Sub
EndCopiedCode:
Hit ctrl+f4.
Hit F5 to run the test.
The 2 SingleLine strings will now be one string and displayed in MultiLineBox.
End Exercise String Concatenation
Exercise Use The Trim Method To Remove Leading And Trailing Spaces
When you load a string from a user's work they might have added some spaces to the beginning of some text or after the text in the TextBox.
If you do not want leading or trailing spaces you remove them using one of the Trim methods.
In this exercise we will...
Type a string into FirstSingleLineBox with spaces in front of the first character of the string and, or, after the last character of the string.
Then use the Trim Method to remove them.
Display the result in SecondSingleLineBox.
Step01;
Clear your workspace ( alt+w, l).
Hit Ctrl+Alt+L for Solution Explorer.
Right click StringsForm.vb and select "View Code".
Modify the code in the TestButton's Click Event Subroutine to look like...
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
Dim TempString As String = ""
TempString = FirstSingleLineBox.Text
SecondSingleLineBox.Text = TempString.Trim()
MultiLineBox.Text = "We did not use this puppy this time"
SecondSingleLineBox.Focus()
End Sub
EndCopiedCode:
Hit ctrl+f4.
Hit F5 to run the test.
You should see your text in the SecondSingleLineBox with the leading and trailing spaces removed.
End Exercise Use The Trim Method To Remove Leading And Trailing Spaces
Exercise Pulling A Substring out of a longer string
You might have a long string you loaded as a result of downloading a Webpage,loaded from a DataBase field or otherwise loaded from another source.
You might want to set a starting point and a length of data to extract from the long string to work with.
This would be the case when you are parsing information from a Webpage.
You would want to use the IndexOf Method to find the StartPosition of the SubString to extract.
Then Use the IndexOf to find the End Position of the String to be extracted.
Subtract the StartPosition from the EndPosition to get the Length.
Use the SubString Method to extract the Contents.
The IndexOf Method is overloaded.
Overloaded means a Method has one name but does diferent things based on what parameters you pass it.
In the preceding example we used the IndexOf method with one string parameter.
The IndexOf method found the string and returned it's start position.
Another Overload of the IndexOf Method allows us to pass a string to find and a integer position within the target text to start looking from.
the search will skip over any characters before the Start Search Position we pass to it.
The 2 forms might look like...
TempString.IndexOf( "Some Text" )
TempString.IndexOf( "SomeText", 3000 )
The second IndexOf statement will start looking for the string from the Index point of 3000 characters into the text.
If there is a hit before the character at position 3000 they are ignored.
The first occurance after position 3000 will trigger a hit.
In this exercise we will...
Type some long text, no enter or tab keys, into MultiLineBox.
Enter the first word or 2 of one of the sentences we typed into FirstSingleLineBox.
Copy the entire sentence from MultiLineBox into SecondLineBox.
Clear your workspace ( alt+w, l).
Hit Ctrl+Alt+L for Solution Explorer.
Right click StringsForm.vb and select "View Code".
Modify the code in the TestButton's Click Event Subroutine to look like...
BeginCopiedCode:
Private Sub TestButton_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TestButton.Click
Dim TempString As String = ""
TempString = MultiLineBox.Text
' see if the starting words are found in the string.
Dim SentenceStartPosition As Integer = _
TempString.IndexOf( FirstSingleLineBox.Text )
If SentenceStartPosition < 0 Then
MessageBox.Show( "Text To Find Was not in MultiLineBox")
FirstSingleLineBox.Focus()
Return
End If
' here we know that our word or words to be found, were found and the start position set.
Dim SentenceEndPosition As Integer = _
TempString.IndexOf( ".", SentenceStartPosition)
If SentenceEndPosition < 0 Then
MessageBox.Show( "No period found after the StartPosition")
FirstSingleLineBox.Focus()
Return
End If
' now we have the start position and end position of the sentence.
' Now calculate the length of the sentence.
Dim SentenceLength As Integer = _
SentenceEndPosition - SentenceStartPosition + 1
' Add 1 to include the end point.
SecondSingleLineBox.Text = _
TempString.SubString( SentenceStartPosition, SentenceLength )
SecondSingleLineBox.Focus()
End Sub
EndCopiedCode:
Hit ctrl+f4.
Hit F5 to run the test.
Type some long text into MultiLineBox.
Type the first word or 2 of one of the sentences in FirstSingleLineBox.
Hit the run button.
The sentence you selected by entering the first words should appear in SecondSingleLineBox.
End Exercise Pulling A Substring out of a longer string
End Unit5 Working With Strings
Section Arithmetic Operators
The following are the arithmetic operators defined in Visual Basic.
^ Operator
This is for exponents.
* Operator
Multiplication
/ Operator
Division
\ Operator
\ Operator (Visual Basic)
Divides two numbers and returns the Integer component of the result.
Mod Operator
Divides two numbers and returns only the remainder.
/ Operator
returns the full quotient, including the remainder, as a floating-point number.
+ Operator
Addition
- Operator
Subtraction
In addition to the basic Arithmatic operators Vb.net uses a large Math Library available in the Framework.
The Namespace is "Math" The Path is,
System.Math
End Section Arithmetic Operators
Section System.String Class
Begin String Class Overview
The Url To Documentation On The String Class,
http://msdn.microsoft.com/en-us/library/s1wwdcbf(v=VS.90).aspx
Remarks
A string is a sequential collection of Unicode characters that is used to represent text.
A String object is a sequential collection of System.Char objects that represent a string.
The value of the String object is the content of the sequential collection, and that value is immutable.
A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object,
use the System.Text.StringBuilder class.
An index is the position of a Char object, not a Unicode character, in a String.
An index is a zero-based, nonnegative number starting from the first position in the string,
which is index position zero.
Consecutive index values might not correspond to consecutive Unicode characters because a Unicode character might be encoded as more than one Char object.
To work with each Unicode character instead of each Char object,
use the System.Globalization.StringInfo class.
Note- Other details about using culture Sensitive settings and strings are on the MSDN Document Page.
There are also some tips on using some of the String Properties and Methods there.
End String Class Overview
Begin String Class Properties
BeginList:
Chars
Holds the character at a specified character position in the current
String object.
Length
Gets the number of characters in the current String.
(Overloaded)
EndList:
End String Class Properties
Begin String Class Methods
BeginList:
EndsWith
Determines whether the end of an instance of String matches a specified string.
IndexOf
Reports the index of the first occurrence of a String, or one or more characters, within this string.
(Overloaded)
Insert
Inserts a specified instance of String at a specified index position in this instance.
IsNullOrEmpty
Indicates whether the specified String object is
Nothing or an Empty string.
Replace
Returns a new string in which all occurrences of a specified Unicode character or String
in this instance are replaced with another specified Unicode character orString.
StartsWith
Determines whether the beginning of an instance of String matches a specified string.
Substring
Retrieves a substring from this instance.
ToLower
Returns a copy of this String converted to lowercase.
ToUpper
Returns a copy of this String converted to uppercase.
Trim
Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.
TrimEnd
Removes all trailing occurrences of a set of characters specified in an array from the current String object.
TrimStart
Removes all leading occurrences of a set of characters specified in an array from the current String object.
endList:
End String Class Methods
End Section System.String Class
Section String Formatting Codes
Begin String Formatting Codes Overview
This is just a very light abstract of formatting codes for reference.
Detail information about the use and examples can be found on the MSDN Documentation pages indicated in this section.
We will use the "ToString()" Method to format our numeric data for display.
End String Formatting Codes Overview
Begin Standard Numeric Format Strings
MSDN Documentation URL,
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.90).aspx
Standard numeric format strings are used to format common numeric types.
A standard numeric format string takes the form Axx, where A
is an alphabetic character called the format specifier, and xx is an optional integer called the precision specifier.
The precision specifier ranges from 0 to 99 and affects the number of digits in the result.
Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string.
End Standard Numeric Format Strings
Begin Standard Format specifiers
Name
Description
"C" or "c"
Currency
Result: A currency value.
Supported by: All numeric types.
Precision specifier: Number of decimal digits.
"D" or "d"
Result: Integer digits with optional negative sign.
Supported by: Integral types only.
Precision specifier: Minimum number of digits.
Default precision specifier: Minimum number of digits required.
"E" or "e"
Exponential (scientific)
Result: Exponential notation.
"F" or "f"
Fixed-point
Result: Integral and decimal digits with optional negative sign.
"G" or "g"
General
Result: The most compact of either fixed-point or scientific notation.
"N" or "n"
Number
Result: Integral and decimal digits, group separators, and a decimal separator with
optional negative sign.
P or p
Percent
Result: Number multiplied by 100 and displayed with a percent symbol.
R or r
Round-trip
Result: A string that can round-trip to an identical number.
X or x
Hexadecimal
Result: A hexadecimal string.
Any other single character
Unknown specifier
Result: Throws a FormatException
at run time.
End Standard Format specifiers
Begin Custom numeric format Strings
http://msdn.microsoft.com/en-us/library/0c899ak8(vs.90).aspx
You can create a custom numeric format string, which consists of one or more custom
numeric specifiers, to define how to format numeric data.
A custom numeric format string is any format string that is not a standard numeric format string.
End Standard Format specifiers
Begin Custom numeric format Specifiers
The following table describes the custom numeric format specifiers and displays sample
output produced by each format specifier.
Format specifier
Name
Description
Examples
BeginList:
"0"
Zero placeholder
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
"#"
Digit placeholder
Replaces the pound sign with the corresponding digit if one is present; otherwise,
no digit appears in the result string.
Decimal point
Determines the location of the decimal separator in the result string.
","
Group separator and number scaling
Serves as both a group separator and a number scaling specifier.
As a group separator, it inserts a localized group separator character between each group.
As a number scaling specifier, it divides a number by 1000 for each comma specified.
"%"
Percentage placeholder
Multiplies a number by 100 and inserts a localized percentage symbol in the result string.
"E0"
"E+0"
"E-0"
"e0"
"e+0"
"e-0"
Exponential notation
If followed by at least one 0 (zero), formats the result using exponential notation.
The case of "E" or "e" indicates the case of the exponent symbol in the result string.
The number of zeros following the "E" or "e" character determines the minimum number of digits in the exponent.
A plus sign (+) indicates that a sign character always precedes the exponent.
A minus sign (-) indicates that a sign character precedes only negative exponents.
\
Escape character
Causes the next character to be interpreted as a literal rather than as a custom format specifier.
"string"
Literal string delimiter
Indicates that the enclosed characters should be copied to the result string unchanged.
68 ("# ' degrees'") -> 68 degrees
68 ("#' degrees'") -> 68 degrees
;
Section separator
Defines sections with separate format strings for positive, negative, and zero numbers.
Other
All other characters
The character is copied to the result string unchanged.
68 ("# °") -> 68 °
End Custom numeric format Specifiers
Begin String Formatting Notes
Control Panel Settings
The settings in the Regional and Language Options
item in Control Panel influence the result string produced by a formatting operation.
Those settings are used to initialize the
NumberFormatInfo
object associated with the current thread culture, which provides values used to
govern formatting. Computers that use different settings generate different result
strings.
End String Formatting Notes
End Section String Formatting Codes
Section System.Array Class
Begin ArrayClassOverview
MSDN Array Class Documentation URL,
http://msdn.microsoft.com/en-us/library/czz5hkty(v=VS.90).aspx
Namespace:
System
Provides methods for creating, manipulating, searching, and sorting arrays, thereby
serving as the base class for all arrays in the common language runtime.
An element is a value in an Array. The length of an Array
is the total number of elements it can contain. The rank of an
Array
is the number of dimensions in the
Array. The lower bound of a dimension of an Array
is the starting index of that dimension of the
Array; a multidimensional Array
can have different bounds for each dimension. An array can have a maximum of 32
dimensions.
End ArrayClassOverview
Begin ArrayClassProperties
IsFixedSize
Gets a value indicating whether the Array has a fixed size.
IsReadOnly
Gets a value indicating whether the Array is read-only.
Length
Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
Rank
Gets the zero-based rank (number of dimensions) of the Array.
End ArrayClassProperties
Begin ArrayClassMethods
BinarySearch
Overloaded.
Searches a one-dimensional sorted Array
for a value, using a binary search algorithm.
Clear
Sets a range of elements in the Array to zero,
to false, or to Nothing, depending on the element type.
Clone
Creates a shallow copy of the Array.
ConstrainedCopy
Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
Guarantees that all changes are undone if the copy does not succeed completely.
ConvertAll(Of TInput, TOutput)
Converts an array of one type to an array of another type.
Copy
Overloaded.
Copies a range of elements in one Array to another Array and performs type casting and boxing as required.
CopyTo
Overloaded.
Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array.
CreateInstance
Overloaded.
Initializes a new instance of the Array class.
Exists(Of T)
Determines whether the specified array contains elements that match the conditions defined by the specified predicate.
Find(Of T)
Searches for an element that matches the conditions defined by the specified predicate,
and returns the first occurrence within the entire Array.
FindAll(Of T)
Retrieves all the elements that match the conditions defined by the specified predicate.
FindIndex
Overloaded.
Searches for an element that matches the conditions defined by a specified predicate, and returns the zero-based index of the first occurrence within an Array.
FindLast(Of T)
Searches for an element that matches the conditions defined by the specified predicate,
and returns the last occurrence within the entire Array.
FindLastIndex
Overloaded.
Searches for an element that matches the conditions defined by a specified predicate, and returns the zero-based index of the last occurrence within an Array or a portion of it.
ForEach(Of T)
Performs the specified action on each element of the specified array.
GetLength
Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
GetLowerBound
Gets the lower bound of the specified dimension in the Array.
GetUpperBound
Gets the upper bound of the specified dimension in the Array.
GetValue
Overloaded.
Gets the value of the specified element in the current Array.
IndexOf
Overloaded.
Returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the
Array.
LastIndexOf
Overloaded.
Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the
Array.
Resize(Of T)
Changes the number of elements of an array to the specified new size.
Reverse
Overloaded.
Reverses the order of the elements in a one-dimensional Array or in a portion of the
Array.
SetValue
Overloaded.
Sets the specified element in the current Array to the specified value.
Sort
Overloaded.
Sorts the elements in one-dimensional Array objects.
ToString
Returns a String that represents the current Object.
TrueForAll(Of T)
Determines whether every element in the array matches the conditions defined by the specified predicate.
End ArrayClassMethods
End Section System.Array Class
Section System.IO.File Class
Begin File Class Overview
MSDN File Class Documentation
http://msdn.microsoft.com/en-us/library/3saad2h5(v=VS.90).aspx
Remarks:
The File Class Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
Note- We will not use File Stream objects such as the "StreamReader" nor "StreamWriter" in this Tutorial.
Namespace:
System.IO
.NET Framework Class Library
End File Class Overview
Begin File Class Methods
AppendAllText
Overloaded.
Appends the specified string to the file, creating the file if it does not already exist.
Copy
Overloaded.
Copies an existing file to a new file.
Create
Overloaded.
Creates a file in the specified path.
Delete
Deletes the specified file. An exception is not thrown if the specified file does not exist.
Exists
Determines whether the specified file exists.
GetAttributes
Gets the
FileAttributes
of the file on the path.
GetCreationTime
Returns the creation date and time of the specified file or directory.
GetLastAccessTime
Returns the date and time the specified file or directory was last accessed.
GetLastWriteTime
Returns the date and time the specified file or directory was last written to.
Move
Moves a specified file to a new location, providing the option to specify a new file name.
OpenRead
Opens an existing file for reading.
OpenWrite
Opens an existing file for writing.
ReadAllLines
Overloaded.
Opens a text file, reads all lines of the file into a string array, and then closes the file.
ReadAllText
Overloaded.
Opens a text file, reads all lines of the file into a string, and then closes the file.
Replace
Overloaded.
Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.
SetAttributes
Sets the specified
FileAttributes
of the file on the specified path.
WriteAllLines
Overloaded.
Creates a new file, writes the specified string to the file, and then closes the file.
If the target file already exists, it is overwritten.
WriteAllText
Overloaded.
Creates a new file, write the contents to the file, and then closes the file.
If the target file already exists, it is overwritten.
End File Class Methods
Begin Custom File enumerations
The following table describes the enumerations that are used to customize the behavior of various
File methods.
Enumeration
Description
FileAccess
Specifies read and write access to a file.
FileShare
Specifies the level of access permitted for a file that is already in use.
FileMode
Specifies whether the contents of an existing file are preserved or overwritten,
and whether requests to create an existing file cause an exception.
End Custom File enumerations
Begin Common I/O Tasks
URL To MSDN Document
http://msdn.microsoft.com/en-us/library/ms404278(v=VS.90).aspx
The
System.IO
namespace provides several classes that allow for various actions, such as reading and writing, to be performed on files, directories, and streams.
Some Links on the MSDN Documentation Page that may be of interest...
BeginList:
To do this...
See the example in this topic...
Create a text file.
System.IO.File
Write to a text file.
How to: Write Text to a File
Read from a text file.
How to: Read Text from a File
Append text to a file.
How to: Open and Append to a Log File
File.AppendText
FileInfo.AppendText
Rename or move a file.
File.Move
FileInfo.MoveTo
Delete a file.
File.Delete
FileInfo.Delete
Copy a file.
File.Copy
FileInfo.CopyTo
Get the size of a file.
FileInfo.Length
Get the attributes of a file.
File.GetAttributes
Set the attributes of a file.
File.SetAttributes
Determine whether a file exists.
File.Exists
Read from a binary file.
How to: Read and Write to a Newly Created Data File
Write to a binary file.
How to: Read and Write to a Newly Created Data File
Retrieve a file extension.
Path.GetExtension
Retrieve the fully qualified path of a file.
Path.GetFullPath
Retrieve the file name and extension from a path.
Path.GetFileName
Change the extension of a file.
Path.ChangeExtension
EndList:
End Common I/O Tasks
Begin Common Directory Tasks
To do this...
See the example in this topic...
Rename or move a directory.
Directory.Move
DirectoryInfo.MoveTo
Copy a Directory
How to: Copy Directories
Delete a directory.
Directory.Delete
DirectoryInfo.Delete
Create a directory.
Directory.CreateDirectory
FileInfo.Directory
Create a subdirectory.
DirectoryInfo.CreateSubdirectory
See the files in a directory.
FileInfo.Name
See the subdirectories of a directory.
Directory.GetDirectories
DirectoryInfo.GetDirectories
See all the files in all subdirectories of a directory.
DirectoryInfo.GetFileSystemInfos
Find the size of a directory.
System.IO.Directory
Determine whether a directory exists.
Directory.Exists
End Common Directory Tasks
End System.IO.File Class
Section System.Exception Classs
Begin Exception Class Overview
URL to Exception class Documentation,
http://msdn.microsoft.com/en-us/library/c18k6c59(v=VS.90).aspx
The Exception Class Represents errors that occur during application execution.
Namespace:
System
Usage
Dim instance As Exception
Remarks
This class is the base class for all exceptions. When an error occurs, either the
system or the currently executing application reports it by throwing an exception
containing information about the error. Once thrown, an exception is handled by the
application or by the default exception handler.
Try-Catch Blocks
The common language runtime provides an exception handling model that is based on
the representation of exceptions as objects, and the separation of program code and
exception handling code into
try blocks and catch
blocks, respectively. There can be one or more
catch
blocks, each designed to handle a particular type of exception, or one block designed
to catch a more specific exception than another block.
If an application handles exceptions that occur during the execution of a block of
application code, the code must be placed within a
try
statement. Application code within a
try statement is a try
block. Application code that handles exceptions thrown by a
try block is placed within a catch
statement, and is called a
catch block. Zero or more catch blocks are associated with a
try block, and each catch
block includes a type filter that determines the types of exceptions it handles.
When an exception occurs in a try block, the system searches the associated
catch blocks in the order they appear in application code, until it locates a
catch block that handles the exception.
You put specialized "Catch" blocks before the most general "Exception" Catch Block if you use them.
The Catch for the System.Exception is specified last.
If an exception occurs but no Catch Block to handle the error exists,
the default exception handler handles it and the application terminates.
End Exception Class Overview
Begin Exception Class Properties
Here a few commonly used properties:
BeginList:
Data
Gets a collection of key/value pairs that provide additional user-defined information
about the exception.
Message
Gets a message that describes the current exception.
Source
Gets or sets the name of the application or the object that causes the error.
StackTrace
Gets a string representation of the frames on the call stack at the time the current
exception was thrown.
TargetSite
Gets the method that throws the current exception.
EndList:
End Exception Class Properties
End Section System.Exception Classs
System.Windows.Forms.BindingSource Class
Begin BindingSourceClassOverview
BindingSource Class Documentation URL,
http://msdn.microsoft.com/en-us/library/ms158145(v=VS.90).aspx
Remarks
The BindingSource component serves many purposes. First, it simplifies binding controls on a form
to data by providing currency management, change notification, and other services
between Windows Forms controls and data sources. This is accomplished by attaching
the BindingSource component to your data source using the
DataSource property. For complex binding scenarios you can optionally set the
DataMember
property to a specific column or list in the data source. You then bind controls
to the
BindingSource. All further interaction with the data is accomplished with calls to the
BindingSource component.
End BindingSourceClassOverview
Begin BindingSourceClassProperties
Name
Description
AllowEdit
Gets a value indicating whether items in the underlying list can be edited.
AllowNew
Gets or sets a value indicating whether the
AddNew
method can be used to add items to the list.
AllowRemove
Gets a value indicating whether items can be removed from the underlying list.
Container
Gets the
IContainer
that contains the
Component.
Count
Gets the total number of items in the underlying list.
CurrencyManager
Gets the currency manager associated with this
BindingSource.
Current
Gets the current item in the list.
DataMember
Gets or sets the specific list in the data source to which the connector currently
binds to.
DataSource
Gets or sets the data source that the connector binds to.
Filter
Gets or sets the expression used to filter which rows are viewed.
IsBindingSuspended
Gets a value indicating whether the list binding is suspended.
IsFixedSize
Gets a value indicating whether the underlying list has a fixed size.
IsReadOnly
Gets a value indicating whether the underlying list is read-only.
IsSorted
Gets a value indicating whether the items in the underlying list are sorted.
IsSynchronized
Gets a value indicating whether access to the collection is synchronized (thread
safe).
Item
Gets or sets the list element at the specified index.
List
Gets the list that the connector is bound to.
Position
Gets or sets the index of the current item in the underlying list.
RaiseListChangedEvents
Gets or sets a value indicating whether
ListChanged
events should be raised.
Site
Gets or sets the
ISite
of the
Component.
Sort
Gets or sets the column names used for sorting, and the sort order for viewing the rows in the data source.
SortDescriptions
Gets the collection of sort descriptions applied to the data source.
SortDirection
Gets the direction the items in the list are sorted.
SortProperty
Gets the
PropertyDescriptor
that is being used for sorting the list.
SupportsAdvancedSorting
Gets a value indicating whether the data source supports multi-column sorting.
SupportsChangeNotification
Gets a value indicating whether the data source supports change notification.
SupportsFiltering
Gets a value indicating whether the data source supports filtering.
SupportsSearching
Gets a value indicating whether the data source supports searching with the
Find
method.
SupportsSorting
Gets a value indicating whether the data source supports sorting.
SyncRoot
Gets an object that can be used to synchronize access to the underlying list.
End BindingSourceClassProperties
Begin BindingSourceClassMethods
Add
Adds an existing item to the internal list.
AddNew
Adds a new item to the underlying list.
ApplySort
Overloaded.
Sorts the data source with the specified sort description or descriptions.
CancelEdit
Cancels the current edit operation.
Clear
Removes all elements from the list.
Contains
Determines whether an object is an item in the list.
CopyTo
Copies the contents of the
List
to the specified array, starting at the specified index value.
CreateObjRef
Creates an object that contains all the relevant information required to generate
a proxy used to communicate with a remote object.
Dispose
Overloaded.
EndEdit
Applies pending changes to the underlying data source.
Equals
Determines whether the specified
Object
is equal to the current
Object.
Find
Overloaded.
Find the specified item in the data source.
GetEnumerator
Retrieves an enumerator for the
List
.
GetHashCode
Serves as a hash function for a particular type.
GetItemProperties
Retrieves an array of
PropertyDescriptor
objects representing the bindable properties of the data source list type.
GetLifetimeService
Retrieves the current lifetime service object that controls the lifetime policy for
this instance.
GetListName
Gets the name of the list supplying data for the binding.
GetRelatedCurrencyManager
Gets the related currency manager for the specified data member.
GetType
Gets the
Type
of the current instance.
IndexOf
Searches for the specified object and returns the index of the first occurrence within
the entire list.
InitializeLifetimeService
Obtains a lifetime service object to control the lifetime policy for this instance.
Insert
Inserts an item into the list at the specified index.
MoveFirst
Moves to the first item in the list.
MoveLast
Moves to the last item in the list.
MoveNext
Moves to the next item in the list.
MovePrevious
Moves to the previous item in the list.
Remove
Removes the specified item from the list.
RemoveAt
Removes the item at the specified index in the list.
RemoveCurrent
Removes the current item from the list.
RemoveFilter
Removes the filter associated with the
BindingSource.
RemoveSort
Removes the sort associated with the
BindingSource.
ResetAllowNew
Infrastructure.
ReInitializes the AllowNew property.
ResetBindings
Causes a control bound to the
BindingSource
to reread all the items in the list and refresh their displayed values.
ResetCurrentItem
Causes a control bound to the
BindingSource
to reread the currently selected item and refresh its displayed value.
ResetItem
Causes a control bound to the
BindingSource
to reread the item at the specified index, and refresh its displayed value.
ResumeBinding
Resumes data binding.
SuspEnd Binding
Suspends data binding to prevent changes from updating the bound data source.
ToString
Overloaded.
End BindingSourceClassMethods
Begin BindingSourceClassEvents
AddingNew
Occurs before an item is added to the underlying list.
BindingComplete
Occurs when all the clients have been bound to this
BindingSource.
CurrentChanged
Occurs when the currently bound item changes.
CurrentItemChanged
Occurs when a property value of the
Current
property has changed.
DataError
Occurs when a currency-related exception is silently handled by the
BindingSource.
DataMemberChanged
Occurs when the
DataMember
property value has changed.
DataSourceChanged
Occurs when the
DataSource
property value has changed.
Disposed
Occurs when the component is disposed by a call to the
Dispose
method.
ListChanged
Occurs when the underlying list changes or an item in the list changes.
PositionChanged
Occurs after the value of the
Position
property has changed.
End BindingSourceClassEvents
EndSystem.Windows.Forms.BindingSource Class
Section System.Windows.Forms.Button Class
Begin Button Class Overview
MSDN Button Class Documentation URL,
http://msdn.microsoft.com/en-us/library/system.windows.forms.button(VS.90).aspx
The Button Class is located in the .NET Framework Class Library.
System.Windows.Forms.Button
There are allot of Properties, Methods and Events for the Button Control.
It has all the usual color, size, location and other standard properties.
These are just a few I picked out to help start getting an overview, 50,000 foot, view of the control.
Remarks
A Button can be clicked by using the mouse, ENTER key, or SPACEBAR if the button has focus.
When you display a form using the ShowDialog method, you can use the
DialogResult property of a button to specify the return value of the ShowDialog Function after you click the button and the Dialog window is closed.
In other words, if you create a Dialog Window and it has a button, you can put some value in the Button's DialogResult Property and then read that value from back in the Parent Form or Control.
Normally you can not read values from windows once they are closed and that includes a window opened as a Dialog Window.
Using the DialogResult property of a button you can pass a value back to the Parent Window where you opened the Dialog Window.
You can change the button's appearance using it's Properties.
You can perform operations on the Button with it's Methods.
You can execute code blocks when various Button Related Events occur.
End Button Class Overview
Begin Button Class Properties
BeginList:
BackColor
Get or set the background color.
CausesValidation
Gets or sets a value indicating whether the control causes validation to be performed
on any controls that require validation when it is clicked.
This is one method that can be used when validating user input.
There is an Event that fires when the Button is clicked called Validating where you can put VB Code to test for things like Numeric Values etc...
We will not use this event but just validate user inputs in the Button's Click Event, more on that later.
Cursor
Gets or sets the cursor that is displayed when the mouse pointer is over the control.
DialogResult
Gets or sets a value that is returned to the parent form when the button is clicked.
Enabled
Gets or sets a value indicating whether the control can respond to user interaction.
Font
Gets or sets the font of the text displayed by the control.
ForeColor
Gets or sets the foreground color of the control.
Location
Gets or sets the coordinates of the upper-left corner of the control relative to it's parent.
Margin
Gets or sets the space between controls.
Padding
Gets or sets padding within the control.
Size
Gets or sets the height and width of the control.
TabIndex
Gets or sets the tab order of the control within its container.
TabStop
Gets or sets a value indicating whether the user can give the focus to this control
using the TAB key.
Text
gets or sets the Text to be displayed to a user.
Visible
Gets or sets a value indicating whether the control and all its child controls are
displayed.
End Button Class Properties
Begin Button Class Methods
Focus
Sets input focus to the control.
NotifyDefault
Notifies the Button whether it is the default button of a form so that it can adjust its appearance accordingly.
End Button Class Methods
Begin Button Class Events
Click
Occurs when the control is clicked.
MouseClick
Occurs when the control is clicked by the mouse.
MouseDoubleClick
ccurs when the user double-clicks the Button
control with the mouse.
MouseHover
Occurs when the mouse pointer rests on the control.
Validated
Occurs when the control is finished validating.
Validating
Occurs when the control is validating and before the Validated Event.
End Button Class Events
End Section System.Windows.Forms.Button Class
Section System.Windows.Forms.ListBox Class
Begin ListBox Class Overview
URL to MSDN Documentation,
http://msdn.microsoft.com/en-us/library/t1f8aedx(v=VS.90).aspx
ListBox Class
Namespace:
System.Windows.Forms
Remarks
The ListBox control enables you to display a list of items to the user that the user can select by clicking.
AListBox control can provide single or multiple selections by setting the SelectionMode property.
The ListBox also provides the MultiColumn property to enable the display of items in columns instead of a straight vertical list of items.
The ListBox can hold lists of objects, not just string literals.
End ListBox Class Overview
Begin ListBox Class Properties
The ListBox has all the standard Properties for Colors, Location and Size as well as many others.
Below are a few others of general interest.
BeginList
BorderStyle
Gets or sets the type of border that is drawn around the ListBox.
ColumnWidth
Gets or sets the width of columns in a multicolumn ListBox.
IntegralHeight
Gets or sets a value indicating whether the control should resize to avoid showing partial items.
ItemHeight
Gets or sets the height of an item in the ListBox.
Items
Gets the items of the ListBox.
(This is the collection of the objects displayed, it would be the String Literals in our example later.)
It is considered a property of a ListBox because a list has the property of the collection of objects to be displayed or it wouldn't be a list.
MultiColumn
Gets or sets a value indicating whether the ListBox
supports multiple columns.
ScrollAlwaysVisible
Gets or sets a value indicating whether the vertical scroll bar is shown at all times.
SelectedIndex
Gets or sets the zero-based index of the currently selected item in a ListBox.
SelectedIndices
Gets a collection that contains the zero-based indexes of all currently selected items in the ListBox.
SelectedItem
Gets or sets the currently selected item in the ListBox.
SelectedItems
Gets a collection containing the currently selected items in the
ListBox.
SelectedValue
Gets or sets the value of the member property specified by the
ValueMember property.
SelectionMode
Gets or sets the method in which items are selected in the ListBox.
Note- It can be for one selection at a time or for allowing multiple selections.
Sorted
Gets or sets a value indicating whether the items in the ListBox
are sorted alphabetically before displayed.
Text
Gets or searches for the text of the currently selected item in the
ListBox.
ValueMember
Gets or sets the property to use as the actual value for the items in the ListControl.
EndList:
End ListBox Class Properties
Begin ListBox Class Methods
BeginList:
BeginUpdate
Maintains performance while items are added to the
ListBox
one at a time by preventing the control from drawing until the
EndUpdate
method is called.
ClearSelected
Unselects all items in the ListBox.
EndUpdate
Resumes painting the
ListBox
control after painting is suspended by the
BeginUpdate
method.
FindString Overloaded.
Finds the first item in the
ListBox
that starts with the specified string.
Note- Overloaded means that you can pass this method a varying number of parameters and parameter types.
Exactly what this method does is determined on how many and what types of parameters you pass it.
SetSelected
Selects or clears the selection for the specified item in a ListBox.
EndList:
End ListBox Class Methods
Begin ListBox Class Events
BeginList:
Click
Occurs when the control is clicked.
HelpRequested
Occurs when the user requests help for a control.
KeyDown
Occurs when a key is pressed while the control has focus.
Layout
Occurs when a control should reposition its child controls.
MouseClick
Occurs when you click the mouse on this control.
SelectedIndexChanged
Occurs when the
SelectedIndex
property or the
SelectedIndices
collection has changed.
SelectedValueChanged
Occurs when the
SelectedValue
property changes.
EndList:
End ListBox Class Events
Begin ListBox Notes
When adding, removing or selecting things from a ListBox,
you usually use one of the ListBox Properties called "Items".
This is because some of the properties like the "Items" Property which is a collection of items we add to a ListBox have their own Methods, Properties and Events because they are also defined as "Classes" in the .net Framework.
ListBox1.Items.Add("Something To Display" )
ListBox1.Items.Add( "Another Item To Display" )
We will use this method later in this tutorial.
End ListBox Notes
End Section System.Windows.Forms.ListBox Class
Section System.Windows.Forms.TextBox Class
Begin TextBox Class Overview
The MSDN Document on the TextBox URL,
http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.aspx
Remarks
With the TextBox control, the user can enter text in an application.
Typically, a TextBox control is used to display, or accept as input, a single line
of text.
You can use the
Multiline
and ScrollBars
properties to enable multiple lines of text to be displayed or entered.
Note
You must set the
Multiline
property to true to adjust the height of the TextBox control.
Then you can adjust the height by setting the Size property.
You can limit the amount of text entered into a TextBox control by setting the
MaxLength
property to a specific number of characters.
TextBox controls can also be used to accept passwords and other sensitive information.
You can use the
PasswordChar
property to mask characters entered in a single-line version of the control.
Use the CharacterCasing property to enable the user to type only uppercase, only lowercase, or a combination
of uppercase and lowercase characters into theTextBox control.
To scroll the contents of the TextBox until the cursor (caret) is within the visible
region of the control, you can use the
ScrollToCaret
method. To select a range of text in the text box, you can use the
Select
method.
To restrict text from being entered in a TextBox control, you can create an event
handler for the
KeyDown
event in order to validate each character entered in the control. You can also restrict
all entry of data in a
TextBox control by setting the
ReadOnly
property to true.
End TextBox Class Overview
Begin TextBox Class Properties
Some Properties Of A TextBox
BeginList:
AcceptsReturn
Gets or sets a value indicating whether pressing ENTER in a multiline TextBox control creates a new line of text in the control or activates the default button of the Parent Form.
AcceptsTab
Gets or sets a value indicating whether pressing the TAB key in a multiline text box control types a TAB character in the control instead of moving the focus to the next control in the tab order.
AllowDrop
Gets or sets a value indicating whether the control can accept data that the user drags onto it.
BackColor
Gets or sets the background color of the control.
BorderStyle
Gets or sets the border type of the text box control.
CanUndo
Gets a value indicating whether the user can undo the previous operation in a textbox control.
CharacterCasing
Restricts the Case,of allowed characters entered by the user.
Enabled
Gets or sets a value indicating whether the control can respond to user interaction.
Font
Gets or sets the font of the text displayed by the control.
ForeColor
Gets or sets the foreground color of the control.
HasChildren
Gets a value indicating whether the control contains one or more child controls.
HideSelection
Gets or sets a value indicating whether the selected text in the text box control remains highlighted when the control loses focus.
Lines
Gets or sets the lines of text in a text box control.
Location
Gets or sets the coordinates of the upper-left corner of the control
relative to the container (Form or Parent Control).
MaxLength
Gets or sets the maximum number of characters the user can type or paste into the text box control.
Modified
Gets or sets a value that indicates that the text box control has been modified by the user since the control was created or its contents were last set.
MultiLine
Gets or sets a value indicating whether this is a multiline TextBox.
Name
Gets or sets the name of the control.
PasswordChar
Gets or sets the character used to mask characters of a password in a single-line TextBox.
ReadOnly
Gets or sets a value indicating whether text in the text box is read-only.
ScrollBars
Gets or sets which scroll bars should appear in a multiline TextBox.
SelectedText
Gets or sets a value indicating the currently selected text in the control.
SelectionLength
Gets or sets the number of characters selected in the text box.
Size
Gets or sets the height and width of the control.
TabIndex
Gets or sets the tab order of the control within its container.
TabStop
Gets or sets a value indicating whether the user can give the focus to this control
using the Tab key.
Text
Gets or sets the current text in the TextBox.
TextLength
Gets the length of text in the control.
Visible
Gets or sets a value indicating whether the control and all its child controls are Visible to the user.
WordWrap
Indicates whether a multiline text box control automatically wraps words to the beginning of the next line when necessary.
EndList:
End TextBox Class Properties
Begin TextBox Class Methods
Some Public Methods
BeginList:
AppendText
Appends text to the current text of a text box.
Clear
Clears all text from the text box control.
Copy
Copies the current selection in the text box to the Clipboard.
Cut
Moves the current selection in the text box to the Clipboard.
DeselectAll
Specifies that the value of the SelectionLength property is zero so that no characters are selected in the control.
DoDragDrop
Begins a drag-and-drop operation.
GetFirstCharIndexFromLine
Retrieves the index of the first character of a given line.
GetLineFromCharIndex
Retrieves the line number from the specified character position within the text of the control.
Paste
Replaces the current selection in the text box with the contents of the Clipboard.
Refresh
Forces the control to invalidate its client area and immediately redraw itself and any child controls.
ScrollToCaret
Scrolls the contents of the control to the current caret position.
Select(Int32, Int32)
Selects a range of text in the text box.
SelectAll
Selects all text in the text box.
Undo
Undoes the last edit operation in the text box.
EndList:
End TextBox Class Methods
Begin TextBox Class Events
Some Events Of The TextBox Control
BeginList:
DoubleClick
Occurs when the control is double-clicked.
DragDrop
Occurs when a drag-and-drop operation is completed.
Enter
Occurs when the control is entered.
Note- Opposite of "Leave".
GotFocus
Occurs when the control receives focus.
HelpRequested
Occurs when the user requests help for a control.
KeyDown
Occurs when a key is pressed while the control has focus.
KeyPress
Occurs when a key is pressed while the control has focus.
KeyUp
Occurs when a key is released while the control has focus.
Leave
Occurs when the input focus leaves the control.
Note- (Opposit of Enter).
MouseClick
Occurs when the control is clicked by the mouse.
MouseDoubleClick
Occurs when the control is double clicked by the mouse.
Validated
Occurs when the control is finished validating.
Validating
Occurs when the control is validating and before Validated is fired.
endList:
End TextBox Class Events
End Section System.Windows.Forms.TextBox Class
End Appendix90 Reference Materials
Appendix91 FormsLayout - Pixel Math
There are several ways to position controls on a form.
It is important at first to learn how to do it manually to understand what is going on when a form is being designed and built.
Also we initially want to work in Pixels rather than other measurement units because we can perform manual calculations against the positioning of a control related to the resolution of our screens.
Other more efficient methods exist but this is the fundemental method of calculating a point on your screen for any type of displayed object. You need to understand Pixels and how to calculate the x and y coordinat of a pixel and how that relates to the location of anything displayed on your screen.
So we will use this method in this tutorial.
Suppose we have a form named "MathForm"...
We can define MathForm to have a size of 1000 by 700 Pixels.
This means that it consists of 1000 dots horzontally by 700 dots vertically. Each dot is called a Pixel. Of course the dots are all filled in so it looks like a solid box to a visual person but each dot called a pixel is one point on the form. Each pixel has a location on the form called an address. Each address has an x and y coordinate. The x coordinate tells you how many pixels from the left of MathForm the dot is and the y coordinate tells you how many Pixels from the top the Pixel is.
The position of the first Pixel in the upper left corner has a x,y coordinate position of 0,0.
Thus a pixal located half way across our form and half way down would have a position of 499, 349.
500 is half of the 1000 pixels we specified in the horzontal size property for MathForm ; And, 350 is half the number of pixels we specified for our verticle size.
but, since the addressing is 0 based we have to subtract 1 from each measurement. I just use the numbers 500 and 350 since 1 pixel is pretty much invisible from a real world viewpoint and 500 and 350 is easier to work with than 499 and 349 mentally.
Thus the point, pixel located at 500, 350 is pretty much in the dead middle of our Form.
Objects like TextBoxes, Buttons and other controls are small rectangular boxes we can put on our form so long as we make sure they all fit inside the form which is the black background of 1000 pixels horzontally by 700 pixels vertically; And, the little boxes will not overlap each other.
Note- When you work inside a form the pixel address is relative to the form. That is, the upper left corner of the form is position 0,0. this is not the same as position 0, 0 of the screen since the form could be located anyplace on the screen. In the following discussion we are referring to the pixel coordinates of controls relative to MathForm.
An Example...
We might look at a TextBox. This is a small box you can have some text displayed in or you can type into.
Consider, for now, it has a fixed position and size.
The specified Pixel Address in the controls Location Property will be where the Upper left corner of the TextBox is positioned when Displayed on the Screen.
Perhaps we want a Calculator on MathForm and our first TextBox will be a place to enter the first number. There might be a second TextBox where you can enter a second number and a button to execute a default arithmetic operation.
Envision the entire screen is black.
We want 2 small white boxes positioned someplace on this big black background where we can type in a FirstNumber and a SecondNumber.
We need to arrange the two boxes somehow. We can put one above the other with a little background space between them or we can put them side by side with a little background space between them.
Let's put our two controls side by side at first.
We will have a TextBox to enter afirst number, some black space and another white TextBox to the right of it where we can enter a second number.
We will have to know where to start the SecondNumberTextBox so SecondNumberTextBox does not overlap FirstNumberTextBox.
When we set the properties for FirstNumberTextBox we specify x and y coordinats in it's Location Property.
The x coordinat is how many pixels from the left of the form the FirstNumberTextBox is positioned.
If we add how long the box is, in Pixels, we would have the x coordinat of the right edge of the box.
The SecondNumberTextBox has to start someplace right of this x coordinat not to overlap the FirstNumberTextBox.
This applies to the y coordinat of a control as well which is the height property of a control.
Look at the following example...
FirstNumberTextBox
Position = 100, 50
Size = 75, 25
This says the left edge of our FirstNumberTextBox is 100 pixels from the left of our form and the top edge 50 pixels from the top of the form.
FirstNumberTextBox is 75 pixels long and 25 pixels high.
That means the white box starts at horzontal position 100 and ends at position 174.
100 + 75 - 1 is 174.
Note- we subtract 1 from the answer because the length is inclusive of the start coordinat.
Therefore, our SecondNumberTextBox will have to start at some x coordinat beyond 174 or it will overlap the FirstNumberTextBox.
If you started the SecondNumberTextBox at 175 from the left of the form the two boxes would appear as one long white rectangle because there would be no spaces between the end of the FirstNumberTextBox and the beginning of the SecondNumberTextBox.
So we will start our SecondNumberTextBox a little further to the right so there will be some black background between the 2 boxes.
To allow for 25 pixels of background space between the right edge of FirstNumberTextBox and the left edge of SecondNumberTextBox I use the calculation,
FirstNumberTextBox x value + FirstNumberTextBox length + 25 pixels of background space - 1.
100 + 75 + 25 - 1 = 194.
We subtract 1 because the calculation includes the start position of FirstNumberTextBox, that is known as an Inclusive arithmetic calculation.
We set the Properties...
FirstNumberTextBox Location is 100, 50
FirstNumberTextBox Size 75, 25
SecondNumberTextBox...
Position 200, 50
Size 75, 25
Note- I picked 200 instead of 194 for the x coordinat of SecondNumberTextBox because it is close to 194 and easier to work with mentally.
The above should do the trick nicely.
Now, our boss says he wants the SecondNumberTextBox ligned up directly under the FirstNumberTextBox, sigh, sure boss!
We repeat the process as described above but using the y coordinat instead of the x coordinat.
FirstNumberTextBox starts at y coordinat 50 so to get the bottom edge we add the start y coordinat, 50, to the height, 25 and subtract 1 to get the bottem edge of FirstNumberTextBox.
Then we can just add 20 pixels of background space to this y coordinat to get a starting top edge for SecondNumberTextBox.
We could also just have used the calculation,
50 + 25 + 20 -1 = 94.
The property settings for this senario...
FirstNumberTextBox,
Position 100, 50
Size 75, 25
SecondNumberTextBox,
Position 100, 95
Size 75, 25
The above should do the trick and keep the boss happy - for now.
End Appendix91 FormsLayout - Pixel Math
Appendix92 Useful Hot Keys
Begin WindowEyes:
ctrl+shift+t
Read Title Bar
ctrl+shift+s
Read Summary
Control-Insert-S
Read status line
Control-Insert-T
Read Last Flash and Tooltip
insert-backslash
Redraw
End WindowEyes:
Begin Solution Explorer And General:
Esc
Closes a menu or dialog, cancels an operation in progress, or places focus in the
current document window
Shift-F4
With cursor on Root Folder, Displays the Project property page Window.
Shift-Alt-Enter
Toggles full screen mode.
Alt+w then T
Set new windows you use to be "Tabbed Documents"
Alt+w then l
Close All open windows
Shift-Esc
Closes the current tool window
ctrl+f4
Close a Tabbed Document Window
ctrl+alt+l
Open Solution Explorer
enter Key
with cursor on a Form like Form1.vb, Opens Forms Designer.
For other vb files opens in appropriate Editor.
F7
brings up the Code Editor when cursor is on a VB file or Form like Form1.vb.
Also Switches from the design view to the code view when in Forms Designer.
shift+f7
With cursor on a Form like Form1.vb, opens the Forms Designer.
Also Switches from the Code Editor to design view.
End Solution Explorer And General:
Begin Forms Designer:
F4
Open Properties Window.
Ctrl+Alt+x
Open ToolBox
F7
Switches from the design view to the code view.
Also brings up the Code Editor when cursor is on a file in Solution Explorer.
End Forms Designer:
BeginVB Code Editor:
Ctrl-=
Selects from the current location in the editor back to the previous location in
the navigation history
Ctrl-M + Ctrl-O
Collapse all code to definitions
Ctrl-M + Ctrl-P
Expand all collapsed code Definition blocks.
Ctrl-M + Ctrl+M
Expend or collapse a selected code fragment.
The code collapsed depends on where the cursor is located.
Shift-F7
Switches from the code view to the design view.
Also brings up the Forms Designer when cursor is on a form in solution Explorer.
F12
In VB Code Editor, Just press F12 to go to variable, or object, declaration
And,
Ctrl+- to return back to the piece of code where you were earlier.
Ctrl-K, Ctrl-C
Marks the current line or selected lines of code as a comment.
( Works but WindowEyes also copies text to clipboard which can just be ignored)
Ctrl-K, Ctrl-U
Removes the comment syntax from the current line or currently selected lines of code
(Works as Expected)
End VB Code Editor:
Begin IntelliSense:
Ctrl-Spacebar or ctrl+j
Displays statement completion based on the current language or autocompletes word.
Also, can access IntelliSense under the Edit Menu when it is available for use.
Ctrl-Shift-Spacebar
Displays a tooltip that contains information for the current parameter, based on
the current language
Also available under the Edit menu under the IntelliSense Branch.
End IntelliSense:
End Appendix92 Useful Hot Keys
Appendix93 Some Accessible Techniques
Section The VB Code Window
Begin The Error List
The Error Window will not PopUp until you either bring it up manually or run a test.
Then it can be a pain if you do not want to fix errors right away.
With the Error Window up you can Double Right Mouse Click one of the Errors in the Error List and be taken to the statement causing the error in the Code Editor.
Fix the Error, bring up the Error Window again and repeat the process until you get 0 errors 0 warnings and 0 messages.
Close the error Window with ctrl+f4.
You might have to Alt Tab out and back into the Code editor or Redraw the screen to have Windoweyes start reading correctly in the Code Editor properly again after all Errors are fixed.
You might also find that just hitting ctrl+f4 will ask you to save your work, Hit Escape and that often works as well to start WE reading properly again.
If you have run a test or viewed the Error Window but want to keep typing lines without having the Error Window pop up because you have not finished the line, you are not typing fast enough, try:
Put an apostrophe at the beginning of the line to make it a comment until you are done with the line.
When done and it sounds right remove the apostrophe.
This is also good for pasting a one line statement from another place that you want to modify and that would cause an error if just pasted into your current position.
If you run a test or the Error Window starts popping up allot close the project and ReOpen it.
When you first work on a project the error window will not impact you until you manually bring up the Error Window or run a Test.
End The Error List
Begin Using Collapsed Code Blocks Selecting, Copying, Replacing And Deleting Lines
You can collapse procedures to just a Procedure Tag.
Move cursor into Sub or function then hold down the control key and hit m twice.
Then you can select the Procedure Tag.
Once selected you can do a Copy, Replace or Delete on the Selected Code.
All lines in the collapsed code block will be copied or modified.
To expand the code hold down the control key and hit m twice again.
The ctrl+m+m toggles between expanded and collapsed.
End Using Collapsed Code Blocks Selecting, Copying, Replacing And Deleting Lines
Begin Selecting Large Blocks Of Lines
If you want to select allot of lines but they are not collapsed you can place your cursor on the first line, then do a find on a subsequent line and hit the select to prior navigation hot key to select the entire line block.
Ctrl-=
Then you can perform the Copy, Replace, Delete operation on the block as usual.
End Selecting Large Blocks Of Lines
Begin Finding Variable or Object Declarations
When typing you often want to find something in another part of the code like the name of a class, sub or some parameters or DataTypes.
You can place your cursor on the variable or Object Name and go to the declaration anyplace in the Project.
Press F12 to go to variable, or object, declaration
Then you can copy or note what you want and return directly to the line of code you are working on.
Press Ctrl+- to return back to the piece of code where you were earlier.
End Finding Variable or Object Declarations
End Section The VB Code Window
Section The Properties Window
Hit F4 in the Forms Designer to open it.
You can click the alphabetical button to list Properties or Events in alphabetical order.
Begin Selecting A Control
To change what control is being displayed in the Properties and Event lists,
Tab to the Components ComboBox,
hit Alt+down arrow to open it,
cursor to an object and hit enter on it.
Back Tab to the properties list and verify it is loaded in the Name or Text Properties.
End Selecting A Control
End Section The Properties Window
Section The Forms Designer
Place cursor on a form like Form1.vb and hit shift+f7 or hit enter to open.
Begin set focus to a visible or non-visible control
If you can't tab to a control or it does not read:
Hit f4 to open the Properties Window,
Tab to the Components ComboBox,
hit Alt+down arrow to open it,
cursor to the control you want selected in the designer and hit enter on it,
Back Tab to the properties list and verify it is loaded in the Name or Text Properties.
Hit Escape and you are returned to the Forms Designer with the control selected in the Designer.
End set focus to a visible or non-visible control
End Section The Forms Designer
End Appendix93 Some Accessible Techniques
Appendix94 The Local MSDN Express Library
Open the Main Menu Bar (Alt)
Under the Help Menu click on "Contents"
Expand the Microsoft Express Library 2008 ( Right Cursor on it)
Expand Visual Basic Express (Right Cursor It)
You can read through the subject matter under the embedded branches.
I recommend taking notes, perhaps just copy and paste, topics of interest.
There are allot of branches and SubBranches and getting back to one of them is sometimes tricky if you forget where that little nugget of information is after leaving a topic.
That said, reading through topics of interest will help give you an overview of the language and some features you might want to research further.
End Appendix94 The Local MSDN Express Library
EndOfArticle:
Well, that's it folks!
If you get this far you will be well on your way to learning to program in VB.net. There are a ton of additional features and technicals but if you manage to have slogged through this much the rest should be understandable and doable enough.