WinformBasics, Intro To Strings And Things

  • From: "RicksPlace" <ofbgmail@xxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Wed, 2 Jun 2010 15:13:21 -0400

    Hi: Here is the first article for Visual Basic. It is just to help some of 
the newer folks get up to speed with some very basic operations and concepts.
If you use this article please let me know of suggestions, errors or anything 
else since it is long and I was doing alot of back and forth between Vb.net, 
Microsoft Webpages and the article itself.
It does not try and demonstrate everything, just enough to see how to add a 
Form to the project, drop a couple of controls on it and wire it up dto do 
something. In the process I introduce Variables, Data Types, the "If" statement 
and the use of the system String class to do some things with strings. The next 
article will finish up with Arithmetic, looping, Creating your own classes with 
subs and functions and an example of an array or ListArray.
After that I will consider another series at the Intermediate level that goes 
from ground 0 up to whatever level folks are willing to work on including the 
use of one or more DataBases like Sql Server, MsAcces or Sql Server Compact 
Edition. If you make it through this article and the next you will likely be 
able to follow along the intermediate level project, if we do one. That or you 
will have the termonology and experience to continue your education 
independently.
If you find any problems, have suggestions or get stuck post up on list or 
contact me off list at:
ofbgmail@xxxxxxxxxx
Happy Programming!
Rick USA 
V02 Intro To Strings   And Other Things V00
Note: you can do a find in your text editor to jump to any subject in this 
Index.
If you have any suggestions, corrections or comments either post to the list or 
contact me off list at:
ofbgmail@xxxxxxxxx

Index:
Chapter01 Things To Know
Section01 Introductionn
Section02 Terms And Concepts
OOP;
Object;
VB Variables;
The "If" Conditional Statement;
Comparison And Logical Operators;
The "Comparison Operators";
The "LogicalOperators";
Examples;
StringLiteral;
StringVariable;
chapter02 Reference Materials
Section03 The String Class
Section04 The Button Control Class
Section05 The TextBox Control Class
Section06 FormsLayout - Concepts and Math
Chapter03 Building A Form
Section07 Add A New Form To The Project
Step01 Add The Form;
Step02 Add Labels To The Form;
Step03 Add TextBoxes To The Form ;
Step04 Add A Button To The Form;
Step05 Set "StringsForm" As the Project Default Form;
Step06 Control Setting Notes;
Chapter04 Exercises
Section08 Notes On Exercise Procedures
Section09 Using The String Length Property
Section10 Using The Replace Method
Section11 Using The IndexOf Method
Section12 String Concatenation
Section13 Use The Trim Method To Remove Leading And Trailing Spaces
Section14 Pulling A Substring out of a longer string
*****
Chapter01 Things To Know
Section01 Introduction
In this article we will examine some ways of working with strings.
We will use the TextBox and Button Controls in this article but address them in 
more detail in later articles.
The idea here is to start getting familiar with the IDE, Forms Designer, 
Properties Window  and the Code Editor.
The main subject material, the Examples, will be using String Literals and 
String Variables.
Read through all the material but don't try and memorize it.
There is way too much to memorize and there are tools for getting at things 
quickly that we will look at later.
The take Away is to see how to navigate the IDE, how to use a control like a 
Button to do something and how to use some of the more common Properties and 
Methods of the String Class.
The next article will introduce the use of a ListBox, deal with Arithmetic 
Operations, String formatting of Numbers and Dates, Looping and creating your 
own Class with Functions and Subroutines.
It will expand on some of the concepts of Conditional Statements, the "If" 
statement in this article and use more of the options of the various controls 
we are touching on here.
Once you have a grip on getting around the IDE and what a Project looks like, 
we will end this raw beginners series and you will be ready for the 
Intermediate Level Series I may produce.
In any event you might have enough skills to be able to get a Vb.net book and 
get through it with your screen reader using techniques in this series in place 
of the visual techniques most books offer up.

Section02 Terms And Concepts
OOP;
OOP stands for Object Orientated Programming.
Object;
An Object is an Instance of a block of VB Code that defines the Object.
The fundemental building block of an Object is the "Class".
A "Class has a starting point and an ending point and all code related to the 
Object is encapsulated within the Opening Statement and the End Statement.
For Example:
BeginSampleCode:
Public Class SongClass
' The VB Code describing the properties and methods of a Song goes here.
End Class
The properties would be things like Title, Artist, RecordingLength and anything 
else that you want to use to describe a song.
The Methods might be Play, AddSong, RemoveSong etc...
Play would be the Method holding the VB code to play the song.
AddSong might be a Method holding the VB code to add a song to a DataBase and 
RemoveSong the code to remove a song from a DataBase.
All this code, the Properties and Methods, would be contained, encapsulated, 
between the Public SongClass opening statement and it's related End Class 
Statement.
Encapsulation is one of the fundemental OOP Concepts.
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, general text"

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.
(We will be working with String  Variables and String Literals in this article.)
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.

Data Types:
The list below shows the Visual Basic data types, nominal storage allocation, 
and Possible value ranges.
You might just take a look at them for some color for now. 
we will use only the Integer and String Data Types in this article.

BeginList:
Numeric Data Types;
Integer, 4 bytes, -2,147,483,648 through 2,147,483,647 (signed)
Long (long integer), 8 bytes, -9,223,372,036,854,775,808 through 
9,223,372,036,854,775,807 (9.2...E+18
Short (short integer), 2 bytes, -32,768 through 32,767 (signed)
UInteger, 4 bytes, 0 through 4,294,967,295 (unsigned)
ULong, 8 bytes, 0 through 18,446,744,073,709,551,615 (1.8...E+19
UShort, 2 bytes, 0 through 65,535 

Decimal, 16 bytes, 0 through (+/-)79,228,162,514,264,337,593,543,950,335
Double (double-precision floating-point), 8 bytes, -1.79769313486231570E+308 
through -4.94065645841246544E-324
(Positive 4.94065645841246544E-324 through 1.79769313486231570E+308)
Single (single-precision floating-point), 4 bytes, -3.4028235E+38 through 
-1.401298E-45
(Positive) 1.401298E-45 through 3.4028235E+38 

Other Data Types;
String (variable-length), (class), Depends on implementing platform
0 to approximately 2 billion Unicode characters

Boolean, Depends on implementing platform, True or False

Byte, 1 byte, 0 through 255 (unsigned)
SByte, 1 byte, -128 through 127 (signed)

Char (single character), 2 bytes, 0 through 65535 (unsigned)

Date, 8 bytes, 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on 
December 31, 9999

Object, (class), 4 bytes, on 32-bit platform 8 bytes on 64-bit platform, 
Any type can be stored in a variable of type Object.

User-Defined;
structure, Depends on implementing platform, Each member of the structure has a 
range determined by its data type and independent of the ranges of the other 
members.
EndListt:
Note On Storage;
Computer Memory Consumption:
You can not easily determine how much internal memory some Variables will take 
up. This is because when your program is run on diferent computers it is 
optimized to run on that particular computer. 
The memory may be compressed, ReStructured or spread over diferent segments of 
memory. 
You can read more about internal storage in the Reference Manual if you want to 
dig into it.
It is not applicable in this Tutorial Series.

The If 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
A "If" statement typically begins with the "If" KeyWord and ends with the "End 
If" KeyWord Statement.
The "Else" KeyWord indicates what to do if the "If" condition is not met.

Comparison And Logical Operators;
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.

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:

The "LogicalOperators";
BeginList:
"And" Operator (Visual Basic)
"Not" Operator (Visual Basic)
"Or" Operator (Visual Basic)
"AndAlso" Operator
"OrElse" Operator
"IsFalse" Operator
"IsTrue" Operator
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

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

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

I prefer to use the Comparison Negation symbol "<>":
If MyNumber <> 5 Then
Do Something
Else
Do  something else
End If
It is cleaner and shorter.

I might use the "Not" operator when words are involved so it sounds better.
If Not IsNumeric( MyVariable ) Then
Do Something
End If
We will start introducing the use of the  String and Integer Data Types and 
some "Conditional Operators" in this article.

StringLiteral;
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.

StringVariable;
A String Variable is a variable  that holds a string of text.
You define it and then you can put a string literal in it and you can then use 
that string by just using the name of the String Variable.
For Example:
Dim MyString as String
MyString = "Hello World"
The "Dim" statement defines 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" ).

chapter02 Reference Materials
Section03 The String Class
A String is an object and the Class that defines the String Object is defined 
in the .net Framework Library.
Thus a String Variable is described in that class in terms of Properties 
Methods and Events.
Note: There is another Class called the "StringBuilder" Class but we will not 
be using it in this tutorial to avoid confusion.
The Url To Documentation On The String Class:
http://msdn.microsoft.com/en-us/library/s1wwdcbf(v=VS.90).aspx
On this page the main links are:
String Class
String Methods
String Properties

Some String Properties:
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)
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.
endOfList:
these are some of the most common methods used with String Variables and we 
will look at several of them.

Section04 The Button Control Class
The Button Class is located in the .NET Framework Class Library:
System.Windows.Forms.Button 
MSDN Button Class Documentation URL:
http://msdn.microsoft.com/en-us/library/system.windows.forms.button(VS.90).aspx

Below are a few things I extracted from the MSDN Documents about the button 
Control to add some color and expose some termonology.
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 
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.
some Button Properties:
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.
Some Button 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.
Some Button Events Where You Can Put Code To Execute when the event occurs:
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. 
endOfList:

There are allot of Properties, Methods and Events for the Button Control.
These are just a few I picked out to help start getting an overview, 50,000 
foot, view of the control which we will use a simple version of later.
It shows some of the things related to the 3 main features of an object:
Properties, Methods and Events.

Section05 The TextBox Control Class
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.
Note
Most of the functionality of the TextBox control is inherited from the
TextBoxBase
 class.
Some Properties Of A TextBox:
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.
Some Public Events:
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. 
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. 
endOfList:

You put your code related to the TextBox in the Subroutines related to these 
events. When the event is fired the code you put into the subroutine gets 
executed. 

Section06 FormsLayout - Concepts and Math
There are several ways to position controls on a form.
It is important to learn how to do it manually to understand what is going on 
when a form is being designed and built.
Also we 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 SecondNumberBox so SecondNumberBox does 
not overlap FirstNumberBox.  
When we set the properties for FirstNumberBox 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 FirstNumberBox 
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 SecondNumberBox has to start someplace right of this x coordinat not to 
overlap the FirstNumberBox.
This applies to the y coordinat of a control as well which is the height 
property of a control.
Look at the following example:
FirstNumberBox 
Position = 100, 50
Size = 75, 25
This says the left edge of our FirstNumberBox is 100 pixels from the left of 
our form and the top edge 50 pixels from the top of the form. 
FirstNumberBox 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 SecondNumberBox will have to start at some x coordinat beyond 
174 or it will overlap the FirstNumberBox. 
If you started the SecondNumberBox 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 FirstNumberBox and the beginning of the SecondNumberBox. 
So we will start our SecondNumberBox 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 
FirstNumberBox and the left edge of SecondNumberBox I use the calculation:
FirstNumberBox x value + FirstNumberBox length + 25 pixels of background space 
- 1.
100 + 75 + 25 - 1 = 194.
We subtract 1 because the  calculation includes the start position of 
FirstNumberBox, that is known as an Inclusive arithmetic calculation.
We set the Properties:
FirstNumberBox Location is 100, 50
FirstNumberBox Size 75, 25
SecondNumberBox:
Position 200, 50
Size 75, 25
Note: I picked 200 instead of 194 for the x coordinat of SecondNumberBox 
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 SecondNumberBox ligned up directly under the 
FirstNumberBox, sigh, sure boss!
We repeat the process as described above but using the y coordinat instead of 
the x coordinat.
FirstNumberBox 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 FirstNumberBox.
Then we can just add 20 pixels of background space to this y coordinat to get a 
starting top edge for SecondNumberBox.
We could also just have used the calculation:
50 + 25 + 20 -1 = 94.
The property settings for this senario:
FirstNumberBox:
Position 100, 50
Size 75, 25
SecondNumberBox
Position 100, 95
Size 75, 25
The above should do the trick and keep the boss happy.


Section07 Add A New Form To The Project
OOP is Object oriented and an object does nothing by itself.
the Default Form in a Project is automatically displayed by the RunTime Engine 
but then nothing else happens until some Event is fired Like the user closing 
the Form or, if there is a button on the form, the user clicks the button. 
Therefore we need some way to fire events to demonstrate working with the 
String Class Properties and Methods.
We will add a new form to the project called "StringsForm", add Controls to it 
and work in a Button's Click Event to demonstrate string operations.
There are many objects and most all of them have events. 
But, the most familiar event from a conceptual standpoint is a Button's Click 
Event.
OurFirst Choices to fire an event:
We can add one button for every feature we want to display and process the 
event in each Button's Click Event.
We can create a ListBox to select something to do and then check which 
operation was selected in a Button's Click Event saving having to position a 
bunch of Button Controls on the page.
Another method of picking some event to execute is to use a MenuBar.
A MenuBar on a form is just like the MenuBar you have seen everyplace including 
the Main MenuBar in the IDE Itself.
You would add a MenuBar, some top level Menus like File, Edit, View, Help or 
any Menus you want.
Then you add  MenuItems under each Menu like the Open, Close and Save items 
under the typical File Menu.
Just like the Button Click Event each MenuItem has a Click Event and 
corresponding Subroutine that holds the VB Code to execute when it is clicked.
We will use a ListBox controlalong with a button in the next Article and expand 
on use of the TextBox and Button controls.
We will dig into using Functions And Subroutines ( Called Methods in OOP), as 
well as using a MenuStrip inLater Articles.
In this Article we will just use a single Button and change the code in it's 
Click Event to demonstrate the various String Methods and Properties as we wak 
this tutorial.
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 
fine and it works well to make a label read with a screen reader, at least with 
Windoweyes.
To implement this plan we will:
Add a new form to the project called "StringsForm" and set it's properties.
drop 3 Label Controls on StringsForm and set their properties.
Drop 3 TextBoxes on StringsForm and set their properties.
Drop a Button on StringsForm, set it's properties and, 
add it's Click Event Subroutine to the StringsForm Class.
Note: The code we put into the Click Event Subroutine will get executed when 
ever a user clicks the button.
Finally we will set our new form "StringsForm" to be the Default Form to open 
when the Project is run.

Step01 Add The Form;
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.
Make sure all branches are closed, left cursor any that are open except the 
Root Branch, Directory..
Cursor To the Root Directory "WinformBasics".
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.
StringsForm.vb should now appear in the Solution Explorer Directory.
Hit Enter on StringsForm.vb to open the Forms Designer.
Hit F4 to open the Properties Window.
Note: The Properties Window is where you can set properties of a control you 
add to the Designer.
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 StringsForm.
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, Pressed
Properties Button, Pressed
Events Button
And Text StringsForm so I am back into the Properties list.
You can up and down cursor to read the properties in the Properties List.
Note: It 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.

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.
These are 3 diferent ways of setting the font that will be used as the Default 
Font for your StringsForm Form.
 So, Lets Expand the Font Branch, 
If you cursor up and down you hear the following settings:
NameMicrosoft Sand Sarif
Size 8.25
Unit Point 
Bold False
GDICharSet 0
GdiVerticalFont False 
Italic False
StrikeOut False
Underline False
I cursor toSize, Tab and  set it to 12 in the EditBox by replacing 8.8 manually 
- just typed in 12.
Then I 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.
I Left cursor a few times to close the Font Branch.
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.
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.
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 Window list of properties for the form.
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 "StringsForm" 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.
This is our form. It has no controls on it so it just looks like the screen has 
turned black except for a little space around the edges and a line along the 
top that might say something like StringsForm which is the  TitleBar.
Note: If you change the Text Property  of StringsForm that is what will be 
displayed in the Title Bar.
We will add and position User Interface controls inside this black box named 
"StringsForm".

Step02 Add Labels To The Form;
Hit Enter on StringsForm.vb to open the Designer again.
Open the ToolBox ( Ctrl+Alt+x)
Note: the ToolBox is a sort of treeView Directory where you pick Controls like 
Buttons and TextBoxes to add to the Forms Designer and, thus, your StringsForm.
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.
Go To Top:
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
Text: First String
TabIndex: 1
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
Text: Second String
TabIndex: 3
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
Text: MultiLine Text    
TabIndex: 5
Make a note of the Size Height property for positioning the TextBoxes.
Mine is:  15
Hit ctrl+f4 to return to Designer.

Step03 Add TextBoxes To The Form;
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
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.

Step04 Add A Button To The Form;
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 form.
Note: the words "BeginCopiedCode: and EndCopiedCode" are not part of the actual 
code. I just use them to denote where some code block begins and ends to make 
it clear when using a screen reader.
Modify the code to look like:
BeginCopiedCode:
Public Class StringsForm
Private Sub TestButton_Click( ByVal sender As System.Object,  ByVal e As 
System.EventArgs) Handles TestButton.Click
MessageBox.Show( "You Clicked me!")
End Sub
End Class
EndCopiedCode:
Close all open Windows ( Alt+w, l) and save your work.
Note: I calculated a vertical position for the button as follows:
The First Label / TextBox started at 50, 100
The second one at 50, 200
So I put the button at 50, 300 to keep the vertical spacing relatively even.
This was just easy, not pretty.
Pretty is for later tutorials.
EndNote:

Let's break the VB Code down.
Public Class StringsForm
The above is the opening Tag for the class named StringsForm.
The KeyWord "Public" is a Scope KeyWord. It means thiClass can be used from 
anyplace in the application.
If it were Private it could not. 

Private Sub TestButton_Click( ByVal sender As System.Object,  ByVal e As 
System.EventArgs) Handles TestButton.Click
The above is the opening statement of a Subroutine.
A subroutine begins with the "Sub" statement and ends with a "End Sub" 
statement.
The word "Sub" is a VB Keyword denoting the beginning of a Subroutine.
The word "Private" is called the "Scope" of the Subroutine.
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.
The Word "TestButton_Click" is the name of this Subroutine.
The things inside the Parenthsis are some parameters used by the system.
The"Handles" clause wires up this sub to the event of the Button being clicked.
We will dig into Subroutines in a later tutorial.
For now, a Subroutine begins with the "Sub" statement and ends with the "End 
Sub" statement.

MessageBox.Show( "You Clicked me!")
We typed the above line.
The statement will display the String Literal"You Clicked Me!" 

End Sub
The above is the closing statement of the Click Event Subroutine.

End Class
The above is the closing statement for the StringsForm Class.
Notice how the "MessageBox" statement is encapsulated between the Sub Keyword 
statement and it's corresponding "End Sub" statement.
And, how the entire subroutine is encapsulated in the class's  Opening and 
closing statements.
Encapsulation is one of the main concepts of Object orientated programming.

Step05 Set "StringsForm" As the Project Default Form;
By Default "Form1" will come up when we run the project.
We want to change that so StringsForm comes up as the Default Form when the 
project is run.
Steps;
Hit Alt+w, l to close all windows.
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 and highlight "       StringsForm"
Tab once and hit ctrl+f4 to close the Settings dialog.
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.
If there is an error in the reading order check your TabIndex values and your 
Location settings.
Once it is reading properly continue.

Step07Control Setting Notes;
I usually use a technique of setting label TabIndex values to odd numbers, 1, 
3, 5 in this example.
Then I set the corresponding TextBox to the even numbers 2, 4 and 6.
I find this easier to work with mentally, just a mental standard I use when 
working with manual positioning.

Chapter04 Exercises
Section08 Notes On Exercise Procedures
Note: 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.
We don't want to mess with the formatting characters that are set when these 
keys are active because we are working on String Literals and String Variables 
and will ignore messing with invisible characters until another day.
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.
Finally, 
If you copy and paste the examples into your project for testing, 
The "Sub" Keyword opening statement will wrap.
Private Sub TestButton_Click( ByVal sender As System.Object,  ByVal e As 
System.EventArgs) Handles TestButton.Click
The best way to do that is to copy only the encapsulated code and not the 
opening "Sub" Keyword Statement nor the closing "End Sub" statement.
that means everything between the:
Private Sub TestButton_Click( ByVal sender As System.Object,  ByVal e As 
System.EventArgs) Handles TestButton.Click
Everything inside here is encapsulated in the Subroutine and can be copied.
End Sub
Finally, you really don't have to close the Code Editor before you run a test.
Just put your code into the Subroutine 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 
just as you were when you worked in the Designer and the Properties Window.

Section09 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.
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.

Section10 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.

Section11 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 in MultiLineBox.
If the Character or SubString is not found the method will return -1.

In this exercise we will:
Create a Integer variable named Position.
Note: More on Numerics in the next tutorial.
Save the text we type into MultiLineBox in a String Variable.
Check to see if the text we type into FirstSingleLineBox is in MultiLineBox.
If the Text is found we will replace it with text we type into 
SecondSingleLineBox 
Else, 
we will display a message that the text was not found in a MessageBox 
and, set focus to FirstSingleLineBox.
Exit the Subroutine.
Note: we will dig into the "If" Statement in detail in later tutorials.
For now they should be understandable as simple english  statements.
Replace some text in the TempString variable using the Replace Method.
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 = ""
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.

Section12 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.

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
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.

Section13 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.

Section14 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.

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:
Note: the underscore is the line continuation character in VB.net and I use it 
below for readability of one of the statements.
Also, the apostrophe is the comment character and I use it in the code block as 
well.
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 should appear in SecondSingleLineBox.
Section99 TakeAway
In this tutorial I am only trying to show you how to open a project, Add a Form 
to it and drop some controls on the form and Then, 
add some VB code to your form to do something.
In the process I introduced variables and Data Types, the TextBox and Button 
controls, the "If" statement and the use of the System.String class.
In the next article I will continue expanding on examples, hit on Arithmetic 
operations, Building your own Classes, Looping and String Formatting of numbers 
and dates.
After that you should have enough experience and termonology to continue your 
learning independently or by joining my Intermediate Level tutorial series, if 
I do one, to create an ongoing Vb.net project that starts from the ground up 
and progresses to use at least one DataBase in the process as well as 
demonstrating more advanced features upon request of list members.
Well, Phew! That's All Folks...
Happy Programming!
Rick USA
End Of Article:

In the process I am trying to g

Other related posts:

  • » WinformBasics, Intro To Strings And Things - RicksPlace