Here's all source code from "Visual Basic Express for Dummies." The code is divided into the various chapters in this file. So to find a particular source code example, you can press Ctrl+F and search the for the chapter, or search for some relatively unusual text within the code itself.
CHAPTER 1
With My.Computer.Printers.DefaultPrinter
.WriteLine("This Is a Test")
.Write("Your Name Here:")
.Print()
End With
CHAPTER 2
CHAPTER 3
console.WriteLine(
Dim loanAmount As Double
Dim annualPercentRate As Double
Dim futureValue As Double = 0
Dim payment As Double
Dim totalPayments As Double
loanAmount = CDbl(InputBox("How much do you want to borrow?"))
annualPercentRate = CDbl(InputBox("What is the annual percentage rate of your loan? Enter 8% as .08."))
totalPayments = CDbl(InputBox("How many monthly payments will you make?"))
payment = Pmt(annualPercentRate / 12, totalPayments, -loanAmount, futureValue, DueDate.EndOfPeriod)
MsgBox("Your payment will be " & payment.ToString("C") & " per month.", MsgBoxStyle.OKOnly, "Payments")
Dim aBrush As New SolidBrush(Color.Red)
CHAPTER 4
TextBox1.Text = “Hello”
Dim x as String
X = TextBox1.Lines(2)
TextBox1.Left = 14
Dim s As String
s = TextBox1.Text
Dim s As String = "Here’s some text”
TextBox1.Text = s
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = "Sample text..."
Dim a As String
Dim sr As New System.IO.StreamReader("c:\InitInfo.txt")
a = sr.ReadLine
Dim s1 As Single = CSng(a)
Dim fnt As New Font("Times New Roman", s1)
TextBox1.Font = fnt
'get the color
a = sr.ReadLine
Dim c As Color
c = System.Drawing.Color.FromName(a)
TextBox1.ForeColor = c
sr.Close()
TextBox1.Select(0, 0) 'turn off TextBox selection bug
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Dim sw As New System.IO.StreamWriter("C:\InitInfo.txt")
'each time you WriteLine, a carriage return (Enter keypress)
'is added automatically
sw.WriteLine("42")
sw.WriteLine("yellow")
sw.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = "Sample text..."
Using aParser As New System.Text.Parsing.TextFieldParser("c:\ InitInfo.txt")
aParser.TextFieldType = System.Text.Parsing.FieldType.Delimited
' the vbCr means that the data -- size, then color -- are
'separated by carriage return characters.
'In other words, each item of data is on its own separate line
'in the .txt file
aParser.Delimiters = New String() {vbCr}
Dim s As String()
Try
'get the size
s = aParser.ReadFields()
Dim s1 As Single = CSng(s(0))
Dim fnt As New Font("Times New Roman", s1)
TextBox1.Font = fnt
'get the color
s = aParser.ReadFields()
Dim c As Color
c = System.Drawing.Color.FromName(s(0))
TextBox1.ForeColor = c
Catch ex As System.Text.Parsing.MalformedLineException
MsgBox("There was a problem with the data: " & ex.Message)
End Try
End Using
TextBox1.Select(0, 0) 'turn off TextBox selection bug
End Sub
Dim fnt As New Font("Verdana", 22)
TextBox1.Font = fnt
Dim c As Color
c = System.Drawing.Color.FromName("blue")
TextBox1.ForeColor = c
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim aParser As Object = My.Computer.FileSystem.OpenTextFieldParser _
("C:\test.txt")
aParser.TextFieldType = System.Text.Parsing.FieldType.Delimited
aParser.delimiters = New String() {vbCr}
Dim s As String() 'this is a string array
Dim s1 As String 'this is an ordinary, single string
While Not aParser.EndOfData
s = aParser.ReadFields()
For Each s1 In s
MsgBox(s1)
Next
End While
End Sub
CHAPTER 5
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
End
End Sub
Sub testit()
MsgBox("A new Sub")
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
testit()
End Sub
Sub testit(ByVal s As String)
MsgBox(s)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
testit("Call Home")
End Sub
MsgBox (“Hello”)
Dim s As String
s = InputBox("What's your name?")
Debug.WriteLine(s)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim N As String = "This"
MsgBox(N)
End Sub
Public Sub TryIt()
MsgBox(N)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim n As Integer
Static x As Integer
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim X As Integer
X = 12
X = X + 5
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim X As Integer
MsgBox(X)
End Sub
Dim x As Integer
Sub Iterate()
Dim I, A As Integer
For I = 1 To 4
A = A + I
Next I
MsgBox(A)
End Sub
Sub Iterate()
Dim a As String
For i = 1 To 12
a = a & i & " "
Next i
MsgBox a
End Sub
Sub Iterate()
Dim a As String
For i = 1 To 12 Step 2
a = a & i & " "
Next i
MsgBox a
End Sub
For i = –10 To –20 Step 2
MsgBox "loop"; i
Next
Sub Nested()
Dim a, cr As String
Dim I, J As Integer
cr = vbCrLf ' move down one line
For I = 1 To 2
For J = 1 To 3
a &= " " & J & cr
Next J
Next I
MsgBox(a)
End Sub
If n > 500 Then Exit For
Sub Iterate()
Dim a, cr As String
cr = vbCrLf ' move down one line
Dim y As Integer
Do While y < 11
y = y + 1
a = a & y & cr
Loop
MsgBox(a)
End Sub
Do Until y = 11
‘Some behaviors
Loop
Do
‘Some behaviors
Loop While Y < 11
Do
‘Some behaviors
Loop Until Y = 11
While X < 7
‘Some behaviors
Wend
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim F As System.Drawing.FontFamily
For Each F In System.Drawing.FontFamily.Families
Debug.WriteLine(F.Name)
Next
End Sub
Sub Branching()
Dim response, m As String
Response = InputBox("How many calories did you take in today?")
If Response > 2200 Then
m = "Keep that up and you'll have to buy new pants. Your bad self."
Else
m = "Good self-control on your part."
End If
MsgBox(m)
End Sub
If X = "Bob" Then
MsgBox "Hello Bob"
ElseIf X = "Billy" Then
MsgBox "Hello Billy"
ElseIf X = "Ashley" Then
MsgBox "Hello Ashley"
End If
Sub Branching()
Dim Reply As String, Password As String = "sue"
Reply = InputBox("What is the password?")
If Reply <> Password Then MsgBox("Access Denied") : End
MsgBox("Password verified as correct. Please continue.")
End Sub
If InputBox("Enter your age, but it's optional") <> "" Then
MsgBox("Thank you for responding")
End If
If CarStatus = burning, Then get out of the car.
Select Case CarStatus
Case Steaming
Let radiator cool down.
Case Wobbling
Check tires.
Case Skidding
Steer into skid.
Case Burning
Leave the car.
End Select
Dim Response As String = InputBox("What's your favorite color?")
Select Case LCase(Response)
Case "blue"
MsgBox("We have three varieties of blue")
Case "red"
MsgBox("We have six varieties of red")
Case "green"
MsgBox("We have one variety of green")
Case Else
MsgBox("We don't have " & Response & ", sorry.")
End Select
Dim X As Integer = InputBox("Your weight, please?")
Select Case X
Case Is < 200
'(put one or more commands here)
MsgBox("Good for you")
Case Is < 300
'(put one or more commands here)
MsgBox("Not too bad.")
End Select
Dim Reply As String = LCase(InputBox("Type in your last name."))
Select Case Reply
Case "a" To "m"
MsgBox("Please go to the left line.")
Case "n" To "z"
MsgBox("Please go to the right line.")
End Select
Case "a" To "l", "gene", NameOfUser
CHAPTER 6
Open “C:\Test.Txt” As 5
Dim strFileName As String = “C:\Test.Txt”
Dim objFilename As FileStream = New FileStream(strFileName, FileMode.Open,
FileAccess.Read, FileShare.Read)
Dim objFileRead As StreamReader = New StreamReader(objFilename)
While (objFileRead.Peek() > -1)
textbox1.Text &= objFileRead.ReadLine()
End While
objFileRead.Close()
objFilename.Close()
TextBox1.Select(0, 0)
TextBox1.Text = My.Computer.FileSystem.ReadAllText("C:\Test.Txt")
TextBox1.Select(0, 0)
My.Computer.FileSystem.CopyFile("c:\test.txt", "C:\temp\test.txt")
CopyFile("c:\test.txt", "C:\temp\test.txt")
CHAPTER 7
Dim MyVariable As String
MyVariable = "This is Tuesday."
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Debug.Print("fluor" & "ide")
Debug.Print("2" + "3")
End Sub
Dim n As String = “5”
Dim m As String = “20”
Dim o As String
o = n + m
o = n & m
Dim TopTvPrice As Integer
TopTvPrice = TextBox1.Text
Dim TopTvPrice As Integer
TopTvPrice = TextBox1.Text
Dim UsersAge as Integer
Dim UsersAge As Integer
UsersAge = InputBox (“How old are you?”)
Dim UsersAge, UsersHeight As Integer
Dim UsersName, Nickname As String
Dim UsersName As String, UsersHeight As Integer
Dim UsersAge As Integer = 21
Option Explicit Off
UsersAge = InputBox (“How old are you?”)
If UsersAge < 50 Then MsgBox ("You're too young to join AARP, pup.")
Dim TVShow as String
TVShow = “Barney”
TVShow = “Five-O”
MyTVShow = PopularShow
TopTvPrice = TextBox1.Text
Dim Msg, Result As String
Result = InputBox("Please type your first name.")
Msg = "Thank you, " & Result
MsgBox(Msg)
Dim Result As String
Result = InputBox("Please type your first name.")
Result = "Thank you, " & Result
MsgBox(Result)
Dim Result As String
Result = InputBox("Please type your first name.")
Msgbox("Thank you, " & Result)
A = 233
A = A + 1
A = A + 1
A += 1
A *= 4
A -= 1
Dim Brother as String
Brother = "Tom"
Brother &= " and Bob"
Dim MyLittleNumber As Integer
Dim MyBigNumber As Long
Dim s As String
Dim i As Integer = 1551
s = CStr(i)
MsgBox(s)
Dim s As String
Dim i As Integer = 1551
s = Convert.ToString(i)
MsgBox(s)
Dim s As String
Dim i As Integer = 1551
s = CType(i, String)
MsgBox(s)
Dim UsersAge As Integer
Dim Msg As String
If UsersAge < 50 Then
Msg = "You "
Else
Msg = "You do not "
End If
Msg &= "qualify for reduced term insurance."
MsgBox(Msg)
Dim Msg, A As String
A = "Rudolpho"
If A Like "Ru*" Then Msg = "Close Enough"
MsgBox(Msg)
Dim A As Boolean
A = "Nora" Like "?ora" : MsgBox(A)
Dim A As Boolean
A = "Nora" Like "F?ora" : MsgBox(A)
If “David” Like “*d” Then
If “Empire” Like “??[n-q]*” Then
If “Empire” Like “??[!n-q]*” Then
If B + A > 12 Then
If PageNumber Mod 5 = 0 Then
FontBold = True
Else
FontBold = False
End If
If BettysAge > 55 And JohnsAge > 50 Then
If TomsMother = Visiting Or SandysMothersAge > 78 Then
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Static Toggle As Boolean
Toggle = Not Toggle
If Toggle Then MsgBox("See this message every other time you click.")
End Sub
If 5 + 2 = 4 Or 6 + 6 = 12 Then MsgBox("One of them is true.")
If 5 + 2 = 4 And 6 + 6 = 12 Then MsgBox (“Both of them are true.”)
3 * 10 + 5
(3 * 10) + 5
3 * (10 + 5)
3 * ((40/4) + 5)
3 * 10 + 5
CHAPTER 8
UBound(myarray)
myarray.Length
Dim MyArray(10) As String
Console.WriteLine("Ubound, the DIMension is: " & UBound(MyArray))
Console.WriteLine("The Length Property is: " & MyArray.Length)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim MyArray() As String = {"Clark", "Lois", "Jimmy"}
Dim i As Integer
For i = 1 To UBound(MyArray)
Debug.WriteLine(MyArray(i))
Next
End Sub
For i = 0 To UBound(MyArray)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim arrBook(6) As Book 'create the array object variable
Dim i As Integer
'instantiate each member of the array:
For i = 0 To 6
arrBook(i) = New Book()
Next
' set the two properties of one of the array members
arrBook(3).Title = "Babu"
arrBook(3).Description = "This book is large."
Dim s As String = arrBook(3).Title
MsgBox(s)
End Sub
End Class
Public Class Book
Private _Title As String
Private _Description As String
Public Property Title() As String
Get
Return _Title
End Get
Set(ByVal Value As String)
_Title = Value
End Set
End Property
Public Property Description() As String
Get
Return _Description
End Get
Set(ByVal Value As String)
_Description = Value
End Set
End Property
End Class
Array.Sort(myArray)
anIndex = Array.BinarySearch(myArray, "Penni Goetz")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim myarray(4) As String
Dim cr As String = vbCrLf 'carriage return
Dim show As String
Dim i As Integer
Dim anIndex As Integer
Dim r As String
'fill the array with values:
myarray.SetValue("zero", 0)
myarray.SetValue("one", 1)
myarray.SetValue("two", 2)
myarray.SetValue("three", 3)
myarray.SetValue("four", 4)
For i = 0 To 4
show = show & myarray(i) & cr
Next
TextBox1.Text = show & cr & cr & "SORTED:" & cr
Array.Sort(myarray)
show = ""
For i = 0 To 4
show = show & myarray(i) & cr
Next
anIndex = Array.BinarySearch(myarray, "two")
r = CStr(anIndex)
show &= cr & "The word two was found at index number " & r & " within the array"
TextBox1.Text &= show
show = ""
For i = 0 To 4
show = show & myarray(i) & cr
Next
TextBox1.Select(0, 0) 'turn off selection
End Sub
myarray.SetValue("one", 2)
Array.Sort(myarray, StartIndex, LengthOfSubset)
Array.Sort(myarray, 4, 7)
TextBox1.Select(0, 0) 'turn off selection
myarray.Sort(firstarray, secondarray)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim cr As String = vbCrLf 'carriage return
Dim myarray(5) As String
Dim lastnames(5) As String
myarray(0) = "Monica Lewis"
myarray(1) = "Georgio Apples"
myarray(2) = "Sandy Shores"
myarray(3) = "Dee Lighted"
myarray(4) = "Andy Cane"
myarray(5) = "Darva Slots"
TextBox1.Clear()
'create an array of the last names:
Dim i As Integer
Dim x As Integer
Dim s As String
For i = 0 To UBound(myarray)
s = myarray(i)
x = s.IndexOf(" ") 'find blank space
lastnames(i) = myarray(i).Substring(x) 'get last name
TextBox1.Text &= lastnames(i) & cr
Next
TextBox1.Text &= cr & "Sorted by last name:" & cr
myarray.Sort(lastnames, myarray)
For i = 0 To UBound(myarray)
TextBox1.Text &= myarray(i) & cr
Next
TextBox1.Select(0, 0) 'turn off selection
End Sub
Array.Reverse(myarray)
Array.Reverse(myarray, 1, 2)
Public arrList As New ArrayList()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
arrList.Add("ET")
arrList.Add("Pearl Harbor")
arrList.Add("Rain")
ListBox1.Items.AddRange(arrList.ToArray)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
arrList.RemoveAt(1)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(arrList.ToArray)
End Sub
arrList.Remove("Pearl Harbor")
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim RangeOfArrList As ArrayList = arrList.GetRange(0, 2)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(RangeOfArrList.ToArray)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Monkey As New ArrayList()
Monkey.Add("A")
Monkey.Add("B")
Monkey.Add("C")
Monkey.Add("D")
Monkey.Add("E")
Monkey.Add("F")
ListBox1.DataSource = Monkey
End Sub
Dim Monkey As New ArrayList()
Dim MonkeyEnumerator As System.Collections.IEnumerator
Monkey.Add("A")
Monkey.Add("B")
Monkey.Add("C")
Monkey.Add("D")
Monkey.Add("E")
Monkey.Add("F")
MonkeyEnumerator = Monkey.GetEnumerator()
While MonkeyEnumerator.MoveNext()
Debug.WriteLine(MonkeyEnumerator.Current)
End While
Dim i As Integer
For i = 0 To Monkey.Count - 1
Debug.WriteLine(Monkey(i))
Next
Dim Food As New Hashtable()
Food.Add("Lion", "Meat")
Food.Add("Bear", "Meat")
Food.Add("Penguin", "Fish")
Debug.WriteLine(Food.Item("Bear"))
CHAPTER 9
Printer.Print Text1
Printer.Print “This.”
PrintForm
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
With My.Computer.Printers.DefaultPrinter
.HorizontalAlignment = HorizontalAlignment.Center
.WriteLine("This Is a Test")
.HorizontalAlignment = HorizontalAlignment.Left
.Write("Your Name Here:")
.WriteHorizontalLine(0.12)
.WriteLine()
.WriteImage(New Bitmap("c:\small.jpg"))
.Print()
End With
End Sub
My.Computer.Printers.DefaultPrinter.
My.Computer.Printers.DefaultPrinter.FontSize(
My.Computer.Printers.DefaultPrinter.FontSize = 16
.FontSize = 16
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Drawing.Text
Imports System.Drawing.Printing
Function ParseWord() As String
'get the next word from the Text, and return it.
'use Static to retain the cursor position value
‘between calls to this function
Static CurPos As Integer
Dim Word As String
'Return an empty string if we've reached the end of the Text.
If CurPos >= TextBox1.Text.Length Then Return ""
'find first non-space character
While Not System.Char.IsLetterOrDigit(TextBox1.Text.Chars(CurPos))
Word = Word & TextBox1.Text.Chars(CurPos)
CurPos = CurPos + 1
If CurPos >= TextBox1.Text.Length Then Return Word 'end of Text
End While
'build a word from the characters until you hit a space (IsWhiteSpace)
While Not (System.Char.IsWhiteSpace(TextBox1.Text.Chars(CurPos)))
Word = Word & TextBox1.Text.Chars(CurPos)
CurPos = CurPos + 1
If CurPos >= TextBox1.Text.Length Then Return Word 'end of Text
End While
Return Word
End Function
If CurPos >= TextBox1.Text.Length Then
While Not System.Char.IsWhiteSpace(TextBox1.Text.Chars(CurPos)))
Word = Word & TextBox1.Text.Chars(CurPos)
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As
System.Drawing.Printing.PrintPageEventArgs)
Handles PrintDocument1.PrintPage
Dim printerFont As New Font("Arial", 10)
Dim LeftMargin As Integer = PrintDocument1.DefaultPageSettings.Margins.Left
Dim TopMargin As Integer = PrintDocument1.DefaultPageSettings.Margins.Top
Dim txtHeight As Integer = _
PrintDocument1.DefaultPageSettings.PaperSize.Height - _
PrintDocument1.DefaultPageSettings.Margins.Top - _
PrintDocument1.DefaultPageSettings.Margins.Bottom
Dim txtWidth As Integer = _
PrintDocument1.DefaultPageSettings.PaperSize.Width - _
PrintDocument1.DefaultPageSettings.Margins.Left - _
PrintDocument1.DefaultPageSettings.Margins.Right
Dim linesPerPage As Integer = _
e.MarginBounds.Height / printerFont.GetHeight(e.Graphics)
Dim R As New RectangleF(LeftMargin, TopMargin, txtWidth, txtHeight)
Static line As String
Dim Words As String
Dim columns, lines As Integer
Words = ParseWord() 'get the first word
' build a single page of text
' if "" then we've reached the end of the TextBox.Text
' if lines > linesPerPage then skip this and use DrawString to print the page
While Words <> "" And lines < linesPerPage
line = line & Words
Words = ParseWord()
e.Graphics.MeasureString(line & Words, printerFont, _
New SizeF(txtWidth, txtHeight), _
New StringFormat, columns, lines)
End While
If Words = "" And Trim(line) <> "" Then 'finished
'print the last page
e.Graphics.DrawString(line, printerFont, Brushes.Black, R, _
New StringFormat)
e.HasMorePages = False
Exit Sub 'quit because there are no more pages to print
End If
'print page
e.Graphics.DrawString(line, printerFont, Brushes.Black, R, New StringFormat)
e.HasMorePages = True
line = Words
End Sub
Dim linesPerPage As Integer = _
e.MarginBounds.Height / printerFont.GetHeight(e.Graphics)
Dim R As New RectangleF(LeftMargin, TopMargin, txtWidth, txtHeight)
Dim txtHeight As Integer = _
PrintDocument1.DefaultPageSettings.PaperSize.Height - _
PrintDocument1.DefaultPageSettings.Margins.Top - _
PrintDocument1.DefaultPageSettings.Margins.Bottom
Dim txtWidth As Integer = _
PrintDocument1.DefaultPageSettings.PaperSize.Width - _
PrintDocument1.DefaultPageSettings.Margins.Left - _
PrintDocument1.DefaultPageSettings.Margins.Right
While Words <> "" And lines < linesPerPage
line = line & Words
Words = ParseWord()
e.Graphics.MeasureString(line & Words, printerFont, _
New SizeF(txtWidth, txtHeight), _
New StringFormat, columns, lines)
End While
If Words = "" And Trim(line) <> "" Then 'if this is true, then we're finished
'print the last page
e.Graphics.DrawString(line, printerFont, Brushes.Black, R, _
New StringFormat)
e.HasMorePages = False
Exit Sub 'quit because there are no more pages to print
End If
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
PrintDocument1.Print()
End
End Sub
PageSetupDialog1.PageSettings = PrintDocument1.DefaultPageSettings()
If PageSetupDialog1.ShowDialog() = DialogResult.OK Then
PrintDocument1.DefaultPageSettings = PageSetupDialog1.PageSettings
End If
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Drawing.Text
Imports System.Drawing.Printing
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As
System.Drawing.Printing.PrintPageEventArgs) Handles
PrintDocument1.PrintPage
With PrintDocument1.DefaultPageSettings.PaperSize
If PictureBox1.Width < .Width Then
PictureBox1.Left = (.Width - PictureBox1.Width) / 2
Else
PictureBox1.Left = 0
End If
End With
With PrintDocument1.DefaultPageSettings.PaperSize
If PictureBox1.Height < .Height Then
PictureBox1.Top = (.Height - PictureBox1.Height) / 2
Else
PictureBox1.Top = 0
End If
End With
Dim r As Rectangle = New Rectangle(PictureBox1.Left, PictureBox1.Top, _
PictureBox1.Width, PictureBox1.Height)
e.Graphics.DrawImage(PictureBox1.Image, r)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
PrintDocument1.Print()
End
End Sub
With PrintDocument1.DefaultPageSettings.PaperSize
If PictureBox1.Width < .Width Then
PictureBox1.Left = (.Width - PictureBox1.Width) / 2
If PictureBox1.Width < PrintDocument1.DefaultPageSettings.PaperSize.Width Then
PictureBox1.Left = (PrintDocument1.DefaultPageSettings.PaperSize.Width - _
PictureBox1.Width) / 2
Dim r As Rectangle = New Rectangle(PictureBox1.Left, PictureBox1.Top, _
PictureBox1.Width, PictureBox1.Height)
e.Graphics.DrawImage(PictureBox1.Image, r)
CHAPTER 10
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
zum = nara
End Sub
Dim zum As String
Dim nara As String
Dim a As Double, b As Double
a = 112
b = a / 2
b = b + 6
Dim a As Double
a = 112
Debug.WriteLine(“Variable a now equals: “ & a)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Try
Dim sr As New System.IO.StreamReader("c:\myfile.doc")
Catch er As System.IO.FileNotFoundException
MsgBox(er.ToString)
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Try
Dim sr As New System.IO.StreamReader("c:\myfile.doc")
Catch er As system.IO.FileNotFoundException
MsgBox("No file named myfile.doc was found on Drive C:")
End Try
End Sub
Try
‘watch the line(s) of code here for any problems
Catch a type of error
‘ insert line(s) of code here to handle that particular error
Catch another type of error
‘ insert line(s) of code here to handle that second error
Finally
‘insert optional line(s) of code here that you want executed
‘within the Try structure
End Try
‘ Start of Try structure
If there was an error Then ‘Catch
React in some way to this error
End If ‘End of Catch code block
If there was a different error Then ‘Catch
React in some way to this error
End If ‘End of Catch code block
‘ End of Try structure
Catch er As DivideByZeroException
er.Message
er.ToString
Try
tryStatements
[Catch1 [exception [As type]] [When expression]
catchStatements1
[Exit Try]
Catch2 [exception [As type]] [When expression]
catchStatements2
[Exit Try]
...
Catchn [exception [As type]] [When expression]
catchStatementsn]
[Exit Try]
[Finally
finallyStatements]
End Try
Try
Dim sr As New System.IO.StreamReader("c:\xxxxx")
Catch er As Exception
'Respond to any kind of error.
End Try
objMainKey.Close()
objFileRead.Close()
objFilename.Close()
Dim e As Exception
e = New Exception("F problem")
Throw e
Throw New Exception("Problem in the Addition function")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Try
IsItBob("Chris") ‘call the procedure
Catch er As Exception ‘find out if there was an error thrown back at us
MsgBox(er.ToString) ‘if there was an error thrown, display it
End Try
End Sub
Sub IsItBob(ByVal s As String)
Dim er As Exception
If s <> "Bob" Then ‘they sent the wrong name!
er = New Exception("This Function needs the name Bob")
‘create an exception variable
Throw er ‘throw it back to the caller
End If
End Sub
CHAPTER 11
CHAPTER 12
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'NorthwindDataSet.Employees'
'table. You can move or remove it, as needed.
Me.EmployeesTableAdapter.Fill(Me.NorthwindDataSet.Employees)
End Sub
Private Sub bindingNavigatorSaveItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
bindingNavigatorSaveItem.Click
If Me.Validate Then
Me.CustomersBindingSource.EndEdit()
Me.CustomersTableAdapter.Update(Me.NorthwindDataSet.Customers)
MsgBox("Your changes were saved.")
Else
System.Windows.Forms.MessageBox.Show(Me, _
"Validation errors occurred.", "Save", _
System.Windows.Forms.MessageBoxButtons.OK, _
System.Windows.Forms.MessageBoxIcon.Warning)
End If
End Sub
Private Sub BindingNavigatorSaveItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
BindingNavigatorSaveItem.Click
Dim DataChanges As NwindDataSet.CustomersDataTable
DataChanges = _
CType(NwindDataSet.Customers.GetChanges(DataRowState.Modified), _
NwindDataSet.CustomersDataTable)
Try
If Not DataChanges Is Nothing Then
CustomersTableAdapter.Update(DataChanges)
MsgBox("Change to database.")
End If
Catch ex As Exception
MsgBox("Error attempting to save your changes to the database: " & _
ex.ToString)
Finally
If Not DataChanges Is Nothing Then
DataChanges.Dispose()
End If
End Try
End Sub
CHAPTER 13
Imports System.Data
Imports System.XML
Imports System.Xml.XmlDataDocument
Imports System.Data.OleDb
Imports System.Data.SqlTypes
Imports System.Data.SqlDbType
Imports System.Data.SqlClient
Public Class Form1
Dim ds As New dataset(), dr As DataRow, dt As DataTable
'holds a deleted record
Dim titlehold As String, descriptionhold As String
'holds the current filenames
Dim schemafilepath As String, datafilepath As String
'holds the total records and current record number
Dim TotalRows As Integer, CurrentRow As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Create a new table named Recipes with title and description
‘(the description of the actual recipe) columns.
dt = New DataTable("Recipes")
dt.Columns.Add("title", GetType(String))
dt.Columns.Add("description", GetType(String))
ds.Tables.Add(dt)
' stick some data into the first record's two columns
dr = dt.NewRow()
dr!title = "First Test Recipe"
dr!description = "Instructions on making popular pies..."
dt.Rows.Add(dr)
'save the structure (schema) of this dataset
ds.WriteXmlSchema("c:\Recipesdataset.xml")
'save the actual data that's currently in this dataset
ds.WriteXml("c:\RecipesData.xml")
Debug.WriteLine("dataset Loaded. ")
Debug.WriteLine("Number of Tables: " & ds.Tables.Count)
Dim s As String
s = ds.Tables(0).Columns.Count.ToString
Debug.WriteLine("Table 1 has " & s & " columns")
s = ds.Tables(0).Rows.Count.ToString()
Debug.WriteLine("Table 1 currently has " & s & " rows" & "(" & s & _
" records of data)")
dt = ds.Tables(0)
For Each dr In dt.Rows
Debug.WriteLine("ColumnName: " & dt.Columns(0).ColumnName & " Data: " & _
dr(0).ToString)
'Debug.WriteLine(" ")
Debug.WriteLine("ColumnName: " & dt.Columns(1).ColumnName & " Data: " & _
dr(1).ToString)
Next
End Sub
MsgBox ("Number of Tables: " & ds.Tables.Count)
dt = ds.Tables!Recipes ‘by name
dt = ds.Tables(“Recipes”) ‘same, but an alternative punctuation
dt = ds.Tables(0) ‘same, but here we use the table’s index number
‘rather than its name.
'save the structure (schema) of this dataset
ds.WriteXmlSchema("c:\Recipesdataset.xml")
'save the actual data that's currently in this dataset
ds.WriteXml("c:\RecipesData.xml")
Public Class Form1
Dim ds As New dataset(), dr As DataRow, dt As DataTable
'holds a deleted record
Dim titlehold As String, descriptionhold As String
Dim schemafilepath As String = "C:\recipesdataset.xml"
Dim datafilepath As String = "C:\recipesdata.xml"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Try
'get the structure file
ds.ReadXmlSchema(schemafilepath)
'get the data file
ds.ReadXml(datafilepath)
Catch er As Exception 'if there was a problem opening this file
Throw (er)
Finally
dt = ds.Tables!Recipes ' set dt to point to this table
End Try
TotalRows = dt.Rows.Count
CurrentRow = 0
txtTitle.Text = dt.Rows(CurrentRow).Item(0)
txtDescription.Text = dt.Rows(CurrentRow).Item(1)
End Sub
dt = ds.Tables!Recipes ' set dt to point to this table
TotalRows = dt.Rows.Count
CurrentRow = 0
txtTitle.Text = dt.Rows(CurrentRow).Item(0)
txtDescription.Text = dt.Rows(CurrentRow).Item(1)
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAdd.Click
'if they have no active dataset, refuse to allow a new record:
If ds.Tables.Count = 0 Then
MsgBox("Please Open a dataset, or create one using the New “ & _
“option in the File menu before attempting to add a “ & _
“new record.")
Exit Sub
End If
'if they have an incomplete record, refuse:
If txtTitle Is "" Or txtDescription Is "" Then MsgBox("One of your “ & _
“TextBoxes has no data. You must enter something for the “ & _
“title and something for the description.") : Exit Sub
' stick the new data into the first row's two columns
dr = dt.NewRow()
dr!title = txtTitle.Text
dr!description = txtDescription.Text
dt.Rows.Add(dr)
Me.Text = "Record Added..."
End Sub
dt.Rows.Remove(dt.Rows(CurrentRow))
CurrentRow = CurrentRow - 1
txtTitle.Text = dt.Rows(CurrentRow).Item(0)
txtDescription.Text = dt.Rows(CurrentRow).Item(1)
CurrentRow = CurrentRow + 1
txtTitle.Text = dt.Rows(CurrentRow).Item(0)
txtDescription.Text = dt.Rows(CurrentRow).Item(1)
CHAPTER 14
Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim result As Single
result = CSng(TextBox1.Text) * 1.07
TextBox1.Text = result.ToString
End Sub
Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As
System.EventArgs)
Calendar1.VisibleDate = CDate("12/16/2005")
End Sub