Itroduction To Programming With Visual Basics
Itroduction To Programming With Visual Basics
CONTENTS
Chapter Comments Chapter 2 Visual Basic Controls and Events Exercises 2.2 Visual Basic Controls 11 Exercises 2.3 Visual Basic Events 15 Chapter 3 Variables, Input, and Output Exercises 3.1 Numbers 18 Exercises 3.2 Strings 21 Exercises 3.3 Input and Output 26 Chapter 4 Decisions Exercises 4.1 Relational and Logical Operators 30 Exercises 4.2 If Blocks 31 Exercises 4.3 Select Case Blocks 38 Exercises 4.4 Input via User Selection 42 Chapter 5 General Procedures Exercises 5.1 Function Procedures 47 Exercises 5.2 Sub Procedures, Part I 50 Exercises 5.3 Sub Procedures, Part II 55 Chapter 6 Repetition Exercises 6.1 Do Loops 57 Exercises 6.2 ForNext Loops 62 Exercises 6.3 List Boxes and Loops 68 Chapter 7 Arrays Exercises 7.1 Creating and Accessing Arrays 77 Exercises 7.2 Using LINQ with Arrays 85 Exercises 7.3 Arrays of Structures 89 Exercises 7.4 Two-Dimensional Arrays 99 Chapter 8 Text Files Exercises 8.1 Managing Text Files 106 Exercises 8.2 StreamReaders, StreamWriters, Structured Exception Handling 111 Exercises 8.3 XML 115 Chapter 9 Additional Controls and Objects Exercises 9.1 List Boxes and Combo Boxes 120 Exercises 9.2 Eight Additional Controls and Objects 125 Exercises 9.3 Multiple-Form Programs 132 Exercises 9.4 Graphics 142
Chapter 10 Databases Exercises 10.1 An Introduction to Databases 151 Exercises 10.2 Editing and Designing Databases 164 Chapter 11 Object-Oriented Programming Exercises 11.1 Classes and Objects 165 Exercises 11.2 Working with Objects 172 Exercises 11.3 Inheritance 186 Chapter 12 Web Applications Exercises 12.1 Programming for the Web, Part 1 193 Exercises 12.2 Programming for the Web, Part 2 199 Exercises 12.3 Using Databases in Web Programs 204
Chapter Comments Chapter 1 1. Your instructor might skip this chapter. If so, I recommend that you take a quick look at two items from the chapter. Look at the last question and answer on page 3 to see how the appearance of a program varies with the version of Windows being used. Also, look at the discussion of "Displaying File Extensions" on pages 5 and 6. I recommend that you configure Windows to show all file extensions. Chapter 2 1. On page 44 you are asked to run a program that was downloaded from the Pearson website for the book. All of the programs appearing in Examples and Case Studies can be downloaded from that website. There is never any need for you to manually type in the code for a program in this textbook. The website also contains all the text files, databases, and pictures needed for the exercises. All of these files are contained in the folders Ch02, Ch03, Ch04, and so on. Each chapter file contains a subfolder named Text_Files_for_Exercises which contains the text files needed for that chapters exercises. The folder Ch09 has a subfolder named Pictures that contains picture files. The folders Ch10 and "Ch12" have a subfolder named Databases containing all the databases needed for the exercises. Each program is contained in a folder with a name in the form chaptersection example number. For instance, the program in Chapter 3, Section 1, Example 2 is contained in the folder 3-1-2. Many of the programs make use of a text file in the subfolder Debug of the programs bin subfolder. 2. At the top of page 44, we explain our use of ellipses (...) as place holders for the phrase "ByVal sender As System.Object, ByVal e As System.EventArgs". A program will not run when the phrase is replaced with an ellipsis. However, a program will run if the phrase is simply deleted. Therefore, if you use Ctrl+C to copy code from this Student Solutions Manual and paste it into your own program, the code will execute after you delete the ellipses. 3. Every program you write requires use of the Properties window. By default, the Properties window is docked to the right side of the IDE. You might find the Properties window easier to use if you undock it while setting properties. If you double-click on the Properties windows title bar, the window will become undocked and larger. After you have finished using the Properties window, right-click on its title bar and click on Dock. Note: This process also can be used to undock (and redock) the Toolbar and the Solution Explorer window.
Chapter 3 1. Figure 3.1 on page 70 shows the settings for Options Explicit, Strict, and Infer set to On. Most instructors will recommend that the first two Options be set to On. Option Infer, on the other hand, is controversial. (The default setting is On.) If you want to learn more about the effect of Option Infer, take a quick look at the discussion of local type inference on page 236. 2. On page 77, we discuss line continuation. In earlier versions of Visual Basic, the underscore character was needed to continue a statement onto another line. Beginning with VB2010, the underscore character can be omitted when a line that obviously has a continuation (such as, when the line ends with a comma or an arithmetic operator) and therefore will seldom be needed in the programs you write. Underscore characters frequent appear in the answer section of the book and in the Student Solutions Manual following the word "Handles". This was necessary due to the fact that we must limit the length of lines in a printed page. 3. A discussion of sending output to the printer is presented at the end of Section 3.3. This material is optional. If your instructor decides to skip this topic, you might want to take a quick look (just a few minutes) to see what's involved in printing the output of a program. This material is not needed in the textbook. I included it at the request of some instructors. Chapter 4 1. Section 4.1 is unusual in that you will not be asked to write any programs in the exercise set. However, the concepts presented in this section will be fundamental to the rest of the textbook. 2. In Chapter 3 we used list boxes to display data. In Section 4.4, we show how list boxes are used to allow the user to make selections. Another control used to make a selection from a list, a combo box, will be discussed in Chapter 9. 3. The first two sentences after Figure 4.12 on page 149 should read as follows: When you click on an unselected item in a list box, the SelectedIndexChanged event is raised. When you click on a check box or on an unchecked radio button, the CheckedChanged event is raised.
Chapter 5 1. Except for the three case studies, Function procedures appear in many more programs than Sub procedures. The use of Sub procedures is part of good programming practice, but it is not essential. Any computer program can be written without Sub procedures. However, there are a number of programs in this textbook that would be very difficult to write without Function procedures. 2. The above comment is not intended to diminish the importance of Sub procedures. They are a fundamental component of good program design. However, if you find Sub procedures somewhat confusing at first, don't worry. You will still be able to work the exercises. You will eventually become comfortable with Sub procedures after seeing them used in subsequent chapters. Chapter 6 1. There are two types of loops presented in this chapterDo loops and For...Next loops. A third type of loop, called a For Each loop, will be presented in Section 7.1. 2. Loops have traditionally been used to process lists of data. For instance, loops can be used with a list of numbers to compute the sum of the numbers, the average of the numbers, the largest number in the list and the smallest number in the lists. The algorithms for calculating sums and averages is obvious. In Example 4 of Section 6.3, the maximum value of the numbers in a list box are calculated with the following algorithm: (a) Declare a variable named max. (b) Assign a value to the variable that is guaranteed to be less than or equal to the maximum value in the list. One possibility is to set the value of max equal to the first number in the list. Another possibility requires some knowledge of the number in the list. For instance, if the number are all grades on an exam, the initial value of max can be set to 0. (c) Use a loop to examine the numbers one at a time. Whenever a number is greater than the current value of max, change the value of max to be that number. After the loop has executed, the value of max will be the largest number in the list. Example 4 uses an analogous algorithm to find the smallest number in the list box. These two algorithms appear several times in the textbook in both examples and exercises. 3. Section 6.3 presents techniques for processing lists of data with loops. In Section 7.2, a method for processing lists without using loops will be presented.
Chapter 7 1. A very important idea to take away from Section 7.1 is that there are four ways to fill an array. Let's illustrate the ways by filling an array with the names of the first three presidents.
(a) Dim pres() As String = {"Washington", "Jefferson", "Adams} (b) Dim pres() As String = IO.File.ReadAllLines("Pres.txt"), where the text
file Pres.txt is located in the program's bin\Debug folder of the program and contains three lines (each containing the name of a president).
(c) Dim strVar As String = "Washington,Jefferson,Adams" Dim pres() As String = strVar.Split(","c) (d) Dim pres(2) As String pres(0) = "Washington" pres(1) = "Jefferson" pres(2) = "Adams"
In the first three ways, the array is declared and sized automatically at the same time it is filled. The second and third ways will be the most used in this book. 2. Section 7.3 is perhaps the most challenging section in the book. However, the techniques presented in this section are very powerful and are heavily used later in the book with text files and databases. The techniques also are presented in Section 8.1 in a slightly different form. Some instructors will skip Section 7.3 and rely solely on Section 8.1. 3. Some important text files used in this chapter are as follows: a. Baseball.txt: contains statistics for all of the players in the major league who had at least 350 at bats in 2009. b. Justices.txt: contains all people who served on the U.S. Supreme Court prior to May 2010. c. SBWinners.txt: contains all Super Bowl winners up to and including 2010. Chapter 8 1. The two sections in this chapter are independent of each other. 2. The preliminaries section at the beginning of Section 8.1 can be omitted if you covered Section 8.3. The techniques presented in the preliminaries will take a fair amount of effort to master. However, the payoff will be substantial. 3. Section 8.1 shows some modern techniques for combining lists of data. In earlier versions of Visual Basic, these tasks could only be carried out with complicated algorithms involving loops.
4. Some important data files used in this chapter are as follows: a. Baseball.xml: contains statistics for all of the players in the major league who had at least 350 at bats in 2009. b. Justices.txt: contains all people who served on the U.S. Supreme Court prior to the summer of 2010. Justice Stevens retired in the summer of 2010. If you want to update the file after his replacement is named, change the last entry in his record to 2010 and add a record for the person replacing him. c. Senate111.txt: contains the composition of the U.S. Senate as of May 1, 2010. d. USPres.txt: contains the names of all U.S. Chapter 9 1. Most of Chapter 9 is not needed in the remainder of the book. However, the chapter shows how to use several tools that are familiar to you from major programs you have used. 2. Programs written by professional programmers often use more than one form. Section 9.3 shows how this is done. However, since this is an introductory book, all programs outside of Section 9.3 use only one form. Chapter 10 1. The steps for binding a database to a program may look complicated at first. However, after you get used to it you will find it easy and quick to carry out. Also, when you work several exercises using the same database, you can just bind the database once and write a different event procedure for each exercise. 2. Some important databases used in this chapter are as follows: a. Baseball.accdb: contains statistics for all of the players in the major league who had at least 350 at bats in 2009. b. Justices.accdb: contains all people who served on the U.S. Supreme Court prior to the summer of 2010. c. UN.accdb: contains the composition of the United Nations as of May 1, 2010. d. Exchrate.accdb: contains currency exchange rates in December 2009. Chapter 11 1. This chapter is independent of the rest of the book.
Chapter 12 1. The programs in the chapter are not created with Visual Basic. Most people will use Visual Web Developer that is contained on the DVD packaged with this book. However, if you have a complete version of Visual Studio, you do not have to install Visual Web Developer. The Visual Studio File menu contains the items New Web Site and Open Web Site that you can use to create and access Web programs. 2. Be sure to read the solution to the practice problem in Section 12.3. It shows you how to save a lot of time when writing the programs for the exercise set.
CHAPTER 2 EXERCISES 2.2 1. After a button is clicked it has a blue border. 3. Click on the form to make it the selected object. Click on the Properties window or Press F4 to activate the Properties window. Select the Text property. Type "CHECKING ACCOUNT". 5. Double-click the TextBox icon in the Toolbox. Activate the Properties window. Select the BackColor property. Click on the down-arrow to the right of the Settings box. Click on the Custom tab, and then click on the desired yellow in the palette. Click on the form to see the empty yellow text box. 7. Double-click on the Label icon in the Toolbox. Activate the Properties window, and select the AutoSize property.
Set the AutoSize property to False. Select the Text property and type the requested sentence.
Select the TextAlign property. Click on the down-arrow button to the right of the Settings box, and click on one of the center rectangles. Resize the label so that the sentence occupies three lines. 9. Double-click on the TextBox icon in the Toolbox. Activate the Properties window. Set the Name property to txtLanguage. Select the Text property and type "Visual Basic 2010". Select the Font property and click on the ellipsis to the right of the Settings box. Scroll up the Font list box, and click on Courier New in the Font box. Click OK. Widen the text box to accommodate its text. 11. Double-click on the Button icon in the Toolbox. Activate the Properties window, and select the BackColor property. Click on the down-arrow button to the right of the Settings box. Click on the Custom tab, and then click on the white square in upper-left corner of the palette. Select the Text property and type "PUSH". Select the Font property, and click on the ellipsis. Click on Italic (with XP or Vista) or Oblique (with Windows 7) in the "Font style" list. Click on 24 in the Size box and click OK. Resize the button.
13. Double-click on the Button icon in the Toolbox. Activate the Properties window. Select the Text property and type "PUS&H". Click on the form to see the resulting button. 15. Double-click on the Label icon in the Toolbox. Activate the Properties window. Select the Name property and type "lblAKA". Select the Text property and type "ALIAS". Select the AutoSize property and set it to False. Select the Font property and click on the ellipsis. Click on Italic (with XP or Vista) or Oblique (with Windows 7) in the "Font style" list. Click OK. Select the TextAlign property, click on the down-arrow box to the right of the Settings box, and click on one of the center rectangles. 17. Double-click on the Label icon in the Toolbox. Activate the Properties window, and select the TextAlign property. Click on the down-arrow box to the right of the Settings box, and click on one of the rectangles on the right. Select the AutoSize property and set it to False. Select the Text property, type "VISUAL BASIC", and press Enter. If the words " VISUAL BASIC " are on one line, resize the label until the words occupy two lines. 19. Double-click on the Label icon in the Toolbox. Activate the Properties window, and select the Font property. Click on the ellipsis to the right of the Settings box. Click on Wingdings in the Font box. Click on the largest size available (72) in the Size box. Click OK. Select the Text property and change the setting to a less than sign (<). Click on the label. (Note: If you didn't know that the less than symbol corresponded to a diskette in the Wingdings font, you could double-click on the diskette character in the Character Map, click the Copy button, select the Text property, and press Ctrl+V. The less than character will appear in the Text settings box.) 21. Double-click on the ListBox icon in the Toolbox. Activate the Properties window, and select the BackColor property. Click on the down-arrow button to the right of the Settings box. Click on the Custom tab and click on the desired yellow square in the palette. Click on the form to see the yellow list box.
Student Solutions Manual (Page 13 of 211) 23. In the Solution Explorer window, right click on Form1.vb and select Rename from the context menu. Type frmYellow.vb. Right-click on the form in the Form Designer, and select Properties from the context menu. Click on BackColor property in the Properties window. Click on the down-arrow button in the right part of the Settings box, click on the Custom tab, and click on a yellow square. 25. Begin a new project. Change the text in the form's title bar to "Dynamic Duo". Place two buttons on the form. Position and resize the buttons as shown. Enter Batman as the text of the first button, and enter Robin as the text of the second button. Increase the font size for both buttons to 14. 27. Begin a new project. Change the text in the form's title bar to "Fill the Blank". Place a label, a text box, and another label on the form at appropriate locations. Change the Text setting of the first label to "Im the king of the" and the Text setting of the second label to "A Quote by Leonardo DiCaprio". 29. Begin a new project. Change the text in the form's title bar to "Uncle's Advice". Place five labels and three buttons on the form. Change the Text setting of each label as indicated. Change the settings of the buttons' Text properties to "1", "2", and "3". Resize and position the labels and buttons. 33. 1 35. Each arrow key moves the text box in the indicated direction.
37. Pressing the right and left arrow keys widens and narrows the text boxes, buttons, and list boxes in the group of selected controls. The up and down arrow keys shorten and lengthen the buttons and list boxes in the group. The arrow keys have no effect on the labels, and only the left and right arrow keys affect the text boxes.
39. Drag a label and a list box onto the form. Click on the label. Hold down the Ctrl key and click on the list box. (You have now selected a group of two controls.) In the Properties window, click on the plus sign (in XP) or the right-pointing triangle (Vista or Windows 7) to the left of the Font property. Click on the Size property, change the setting to 12, and press the Enter key. (Alternative: Replace the last three lines with the following steps.) In the Properties window, select the Font property. Click on the ellipsis button to the right of the Settings box. Click on 12 in the Size list and click OK. 41. The label is positioned just to the left of the text box, and the middles of the two controls are aligned. 43. Center refers to the midpoint horizontally, whereas middle refers to the midpoint vertically. 45. First blue snap line: tops of the two controls are aligned Purple snap line: middles of the two controls are aligned Second blue snap line: bottoms of the two controls are aligned 47. The setting is cycling through the different available colors.
EXERCISES 2.3 1. The word "Hello" 3. The word "Hello" on an orange-colored background 7. The word "Hello" in green letters 11. Form1.Text should be Me.Text.
9. The word "Hello" on a gold background. 13. Red should be replaced with Color.Red.
15. Font.Size is a read-only property. The statement txtOutput.Text = txtBox.Font.Size is valid since it is reading the value of txtBox.Font.Size. However, txtBox.Font.Size = 20 is not valid since it is setting the value of txtBox.Font.Size.
17. lblTwo.Text = "E.T. phone home." 19. txtBox.ForeColor = Color.Red txtBox.Text = "The stuff that dreams are made of." 21. txtBox.Enabled = False 25. btnOutcome.Enabled = True 23. lblTwo.Visible = False 27. txtBoxTwo.Focus()
29. The Enter event occurs when a control gets the focus.
31. Private Sub Label1_Click(...) Handles Label1.Click lstOutput.Items.Add("Click") End Sub Private Sub Label1_DoubleClick(...) Handles Label1.DoubleClick lstOutput.Items.Add("Double Click") End Sub
Whenever the DoubleClick event is raised, the Click event is also raised.
33. Private Sub btnLeft_Click(...) Handles btnLeft.Click txtBox.Text = "Left Justify" txtBox.TextAlign = HorizontalAlignment.Left End Sub Private Sub btnCenter_Click(...) Handles btnCenter.Click txtBox.Text = "Center" txtBox.TextAlign = HorizontalAlignment.Center End Sub Private Sub btnRight_Click(...) Handles btnRight.Click txtBox.Text = "Right Justify" txtBox.TextAlign = HorizontalAlignment.Right End Sub
CHAPTER 3 EXERCISES 3.1 1. 12 13. Valid 3. .125 5. 8 7. 2 17. 10 9. 1 11. Not valid 19. 16 21. 9
23. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add((7 * 8) + 5) End Sub 25. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add(0.055 * 20) End Sub 27. Private Sub btnCompute_Click(...) Handles btnCompute.Click lstOutput.Items.Add(17 * (3 + 162)) End Sub 29. x Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim x, y As Double x = 2 y = 3 * x x = y + 5 lstResults.Items.Clear() lstResults.Items.Add(x + 4) y = y + 1 End Sub 31. 6 33. 1 8 9 35. 1 64 37. 2 15 0 2 2 11 11 11 11 y 0 0 6 6 6 6 7
39. The third line should read c = a + b 41. The first assignment statement should not contain a comma. The second assignment statement should not contain a dollar sign. 43. 9W is not a valid variable name.
47. 10 49. 6 51. 3.128 45. Dim quantity As Integer = 12 53. 3 55. 0 57. 6
71. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim waterPerPersonPerDay, people, days, waterUsed As Double waterPerPersonPerDay = 1600 people = 315000000 days = 365 waterUsed = waterPerPersonPerDay * people * days lstOutput.Items.Add(waterUsed) End Sub
EXERCISES 3.2
1. Visual Basic 3. Ernie 5. flute 13. 5.5 23. 8 7. 123 9. Your age is 21. 17. WALLAWALLA 25. True
11. A ROSE IS A ROSE IS A ROSE 19. ABC 2 4 55 mph STU 21. 12 MUNICIPALITY city 6
15. goodbye
(0 through 7)
27. The variable phoneNumber should be declared as type String, not Double. 29. End is a keyword and cannot be used as a variable name. 31. The IndexOf method cannot be applied to a number, only a string.
33. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim firstName, middleName, lastName As String Dim yearOfBirth As Integer firstName = "Thomas" middleName = "Alva" lastName = "Edison" yearOfBirth = 1847 txtOutput.Text = firstName & " " & middleName & " " & lastName & ", " & yearOfBirth End Sub 35. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim publisher As String publisher = "Prentice Hall, Inc." txtOutput.Text = "(c) " & publisher End Sub 37. Dim str As String 'Place in the Declarations section of the program
41. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim cycling, running, swimming, pounds As Double cycling = CDbl(txtCycle.Text) running = CDbl(txtRun.Text) swimming = CDbl(txtSwim.Text) pounds = (200 * cycling + 475 * running + 275 * swimming) / 3500 pounds = Math.Round(pounds, 1) txtWtLoss.Text = pounds & " pounds were lost." End Sub 43. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim revenue, expenses, income As Double revenue = CDbl(txtRevenue.Text) expenses = CDbl(txtExpenses.Text) income = revenue - expenses txtNetIncome.Text = CStr(income) End Sub
47. Dim number As Integer = 100 'in Declarations section 'Note: the Text property of txtOutput was set to 100 at design time Private Sub btnPressMe_Click(...) Handles btnPressMe.Click number = number - 1 'decrease number by 1 txtOutput.Text = CStr(number) End Sub
51. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim speed, distance As Double distance = CDbl(txtDistanceSkidded.Text) speed = Math.Sqrt(24 * distance) speed = Math.Round(speed, 2) txtEstimatedSpeed.Text = speed & " mph" End Sub
Private Sub btnRecord_Click(...) Handles btnRecord.Click num += 1 sum += CDbl(txtScore.Text) txtScore.Clear() txtScore.Focus() End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click txtAverage.Text = CStr(sum / num) End Sub
55. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim num1, num2, sum As Double num1 = CDbl(txtFirstNum.Text) num2 = CDbl(txtSecondNum.Text) sum = num1 + num2 txtSum.Text = CStr(sum) End Sub Private Sub txtEitherNum_TextChanged(...) Handles _ txtFirstNum.TextChanged, txtSecondNum.TextChanged txtSum.Clear() End Sub
EXERCISES 3.3
1. 1,235 13. $12,346 23. 66.67% 3. 1,234.0 15. ($0.23) 5. 0.0 7. -0.67 9. 12,346.000 11. 12
17. $0.80
19. 7.50%
21. 100.00%
27. 25.6% of the U.S. population 25+ years old are college graduates. 29. The likelihood of Heads is 50% 33. Thursday, November 25, 2010 41. You might win 360 dollars. 47. 31. 10/23/2010 35. 10/2/2011 37. 4/5/2013 39. 29
45. $106.00
Prints the words Hello World using a 10-point bold Courier New font in blue letters 2 inches from the left side of the page and 2 inches from the top of the page. The statement n += 1 is not valid since the value of a named constant cannot be changed.
49.
51. The second line should use CDbl to convert the right-hand side to type Double. 53. FormatNumber(123456) is a string and therefore cannot be assigned to a numeric variable. 55. You must insert .Show, after the word MessageBox.
57. 000 59. LLL000 61. 0-00-000000-&
63. MessageBox.Show("First solve the problem. Then write the code.", "Good Advice") 65. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim begOfYearCost, endOfYearCost As Double Dim percentIncrease As Double begOfYearCost = 200 endOfYearCost = CDbl(InputBox("Enter cost at the end of the year:")) percentIncrease = (endOfYearCost - begOfYearCost) / begOfYearCost txtOutput.Text = "The increase in cost for the year is " & FormatPercent(percentIncrease) & "." End Sub
69. Private Sub Determine_Click(...) Handles btnDetermine.Click Dim dt As Date = CDate(mtbDate.Text) Dim fullDate As String = FormatDateTime(dt, DateFormat.LongDate) Dim position As Integer = fullDate.IndexOf(",") Dim dayOfWeek As String = fullDate.Substring(0, position) txtDayOfWeek.Text = dayOfWeek End Sub 71. Private Sub Determine_Click(...) Handles btnDetermine.Click Dim month, yr As Integer 'month given as 1 through 12 Dim dt, dt2 As Date Dim numDays As Double month = CInt(txtMonth.Text) yr = CInt(mtbYear.Text) dt = CDate(month & "/1/" & yr) dt2 = dt.AddMonths(1) numDays = DateDiff(DateInterval.Day, dt, dt2) txtNumDays.Text = CStr(numDays) End Sub
75. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim principal, intRate, yrs, amt As Double lstOutput.Items.Clear() principal = CDbl(txtPrincipal.Text) intRate = CDbl(txtIntRate.Text) yrs = 10 amt = principal * (1 + intRate) ^ yrs lstOutput.Items.Add("When " & FormatCurrency(principal) & " is") lstOutput.Items.Add("invested at " & FormatPercent(intRate)) lstOutput.Items.Add("for " & yrs & " years, the ") lstOutput.Items.Add("balance is " & FormatCurrency(amt) & ".") End Sub
Private Sub btnPrint_Click(...) Handles btnPrint.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(...) Handles PrintDocument1.PrintPage Dim gr As Graphics = e.Graphics Dim x1 As Integer = ONE_INCH 'use one inch beyond left margin Dim x2 As Integer = CInt(1.5 * ONE_INCH) 'offset for second column Dim x3 As Integer = CInt(2.25 * ONE_INCH) 'offset for third column Dim y As Integer = ONE_INCH 'use one inch top margin Dim font1 As New Font("Courier New", 10, FontStyle.Underline) Dim font2 As New Font("Courier New", 10, FontStyle.Regular) gr.DrawString("% of", font2, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("Rank", font1, Brushes.Black, x1, y) gr.DrawString("Country", font1, Brushes.Black, x2, y) gr.DrawString("WW Users", font1, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("1", font2, Brushes.Black, x1, y) gr.DrawString("USA", font2, Brushes.Black, x2, y) gr.DrawString(FormatPercent(0.16, 1), font2, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("2", font2, Brushes.Black, x1, y) gr.DrawString("China", font2, Brushes.Black, x2, y) gr.DrawString(FormatPercent(0.119, 1), font2, Brushes.Black, x3, y) y += LINE_HEIGHT gr.DrawString("3", font2, Brushes.Black, x1, y) gr.DrawString("Japan", font2, Brushes.Black, x2, y) gr.DrawString(FormatPercent(0.065, 1), font2, Brushes.Black, x3, y) End Sub Private Sub btnPreview_Click(...) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub
9. True
11. True
13. True
15. False
17. False
19. True
21. True
25. False
27. False
29. True
31. Equivalent
35. Equivalent
39. Equivalent
41. a <= b
43. (a >= b) Or (c = d)
[In Exercises 46 through 49, execute a statement of the form txtOutput.Text = Boolean expression.] 47. True 49. False 51. False 53. True 55. True 57. False 59. True
EXERCISES 4.2
1. Less than ten. 3. tomorrow is another day. 9. Hi 5. 10
13. Syntax error. Third line should be If ((1 < num) And (num < 3)) Then 15. Syntax error. Fourth line should be If ((major = "Business") Or (major =
"Computer Science")) Then
17. a = 5
19. message = "Is Alaska bigger than Texas and California combined?" answer = InputBox(message) If (answer.Substring(0, 1).ToUpper = "Y") Then txtOutput.Text = "Correct" Else txtOutput.Text = "Wrong" End If 21. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim cost, tip As Double cost = CDbl(InputBox("Enter cost of meal:")) tip = cost * 0.15 If tip < 1 Then tip = 1 End If txtOutput.Text = "Leave " & FormatCurrency(tip) & " for the tip." End Sub
23. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim num, cost As Double num = CDbl(InputBox("Number of widgets:")) If num < 100 Then cost = 0.25 * num '25 cents each Else cost = 0.2 * num '20 cents each End If txtOutput.Text = "The cost is " & FormatCurrency(cost) & "." End Sub
27. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim s1, s2, s3 As Double '3 scores Dim avg As Double 'average of the two highest scores s1 = CDbl(InputBox("Enter the first of the three scores.")) s2 = CDbl(InputBox("Enter the second of the three scores.")) s3 = CDbl(InputBox("Enter the third of the three scores.")) If (s1 <= s2) And (s1 <= s3) Then 's1 is smallest number avg = (s2 + s3) / 2 ElseIf (s2 <= s1) And (s2 <= s3) Then 's2 is smallest number avg = (s1 + s3) / 2 Else 's3 is smallest number avg = (s1 + s2) / 2 End If txtAverage.Text = CStr(avg) End Sub
31. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim wage, hours, grossPay As Double wage = CDbl(txtHourlyWage.Text) 'Hourly pay hours = CDbl(txtHoursWorked.Text) 'Hours worked If hours <= 40 Then grossPay = wage * hours Else grossPay = (wage * 40) + (1.5 * wage * (hours - 40)) End If txtGrossPay.Text = FormatCurrency(grossPay) End Sub
4.2 Exercise 35
4.2 Exercise 37
37. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click If lblLanguage.Visible Then lblLanguage.Visible = False btnDisplay.Text = "Show Name of Language" Else lblLanguage.Visible = True btnDisplay.Text = "Hide Name of Language" End If End Sub
41. Private Sub Determine_Click(...) Handles btnDetermine.Click Dim dt, dt2 As Date Dim approximateAge As Double dt = CDate(mtbDate.Text) approximateAge = DateDiff(DateInterval.Year, dt, Today) dt2 = dt.AddYears(CInt(approximateAge)) If Today < dt2 Then txtAge.Text = CStr(approximateAge - 1) Else txtAge.Text = CStr(approximateAge) End If End Sub
EXERCISES 4.3
1. The price is $3.75 The price is $3.75 3. Mesozoic Era Paleozoic Era ?
5. The equation has no real solutions. The equation has two solutions. The equation has exactly one solution.
7. Should have a Case clause before the 4th line. 9. Case nom = "Bob" should be Case "Bob" 11. Logic error: >= "Peach" should be >= "PEACH". Syntax error: "ORANGE TO PEACH" should be "ORANGE" To "PEACH". 13. Valid 15. Invalid 17. Valid
19. Select Case a Case 1 txtOutput.Text = "one" Case Is > 5 txtOutput.Text = "two" End Select 21. Select Case a Case 2 txtOutput.Text = "yes" Case Is < 5 txtOutput.Text = "no" End Select
25. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim shapeNum As Integer Dim radius, length, height, width As Double 'Input choice of shape and its dimensions '1. Circle 2. Parallelogram 3. Kite shapeNum = CInt(mtbSelection.Text) 'Mask is 0 Select Case shapeNum Case 1 radius = CDbl(InputBox("Input the radius of the circle: ")) txtArea.Text = CStr(3.141593 * radius ^ 2) Case 2 length = CDbl(InputBox("Input the length of the parallelogram: ")) height = CDbl(InputBox("Input the height of the parallelogram: ")) txtArea.Text = CStr(length * height) Case 3 length = CDbl(InputBox("Input the length of the kite: ")) width = CDbl(InputBox("Input the width of the kite: ")) txtArea.Text = CStr((length * width) / 2) Case Else MessageBox.Show("Your choice is not valid.", "Try Again.") mtbSelection.Clear() End Select mtbSelection.Focus() End Sub
29. Private Sub btnDescribe_Click(...) Handles btnDetermine.Click Dim amountRecovered, payment As Double amountRecovered = CDbl(InputBox("How much was recovered?")) Select Case amountRecovered Case Is <= 75000 payment = 0.1 * amountRecovered Case Is <= 100000 payment = 7500 + 0.05 * (amountRecovered - 75000) Case Is > 100000 payment = 8750 + 0.01 * (amountRecovered - 100000) If payment > 50000 Then payment = 50000 End If End Select txtOutput.Text = "The amount given as reward is " & FormatCurrency(payment) & "." End Sub
EXERCISES 4.4 1. The word "Income" becomes the caption embedded in the top of GroupBox1. 3. The CheckBox1 check box becomes (or remains) unchecked. 5. The radio button becomes (or remains) unselected. 7. The radio buttons caption becomes "Clear All". 9. RadioButton1.Text = "Yes" 11. CheckBox1.Checked = True 15. Yes
17. Private Sub CheckedChanged(...) Handles _ radDeluxe.CheckedChanged, radSuper.CheckedChanged, chkUpgradedVideo.CheckedChanged, chkModem.CheckedChanged, chkMemory.CheckedChanged If radDeluxe.Checked Or radSuper.Checked Then Dim cost As Double = 0 'Add amounts to the cost based upon selections. If radDeluxe.Checked Then cost += 1000 Else 'Super model cost += 1500 End If If chkUpgradedVideo.Checked Then cost += 200 End If If chkModem.Checked Then cost += 30 End If If chkMemory.Checked Then cost += 120 End If txtTotalCost.Text = FormatCurrency(cost) Else MessageBox.Show("You must first select a model!") End If End Sub
19. Private Sub btnVote_Click(...) Handles btnVote.Click If radCandidate1.Checked Then txtVote.Text = "You voted for Kennedy." ElseIf radCandidate2.Checked Then txtVote.Text = "You voted for Nixon." Else txtVote.Text = "You voted for neither." End If End Sub Private Sub btnClear_Click(...) Handles btnClear.Click radCandidate1.Checked = False radCandidate2.Checked = False End Sub
11. The function header should end with "As String", not "As Integer". 13. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim radius, height As Double lstOutput.Items.Clear() radius = CDbl(InputBox("Enter radius of can (in centimeters):")) height = CDbl(InputBox("Enter height of can (in centimeters):")) lstOutput.Items.Add("A can of radius " & radius & " and height " & height) lstOutput.Items.Add("requires " & TinArea(radius, height) & " square centimeters") lstOutput.Items.Add("of tin.") End Sub
Function TinArea(ByVal radius As Double, ByVal ht As Double) As Double 'Calculate surface area of a cylindrical can. Return 6.283 * (radius ^ 2 + radius * ht) End Function
15. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim weight As Double = CDbl(txtWeight.Text) Dim height As Double = CDbl(txtHeight.Text) txtBMI.Text = CStr(BMI(weight, height)) End Sub Function BMI(ByVal w As Double, ByVal h As Double) As Double Return Math.Round((703 * w) / (h ^ 2)) End Function
19. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim weight As Double weight = CDbl(txtWeight.Text) txtOutput.Text = "The cost of mailing the letter was " & FormatCurrency(Cost(weight)) & "." End Sub
Function Ceil(ByVal x As Double) As Double Return -Int(-x) End Function Function Cost(ByVal weight As Double) As Double Return 0.05 + 0.1 * Ceil(weight - 1) End Function
23. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click If IsLeapYear(CInt(mtbYear.Text)) Then 'mask is 0000 txtOutput.Text = mtbYear.Text & " is a leap year." Else txtOutput.Text = mtbYear.Text & " is not a leap year." End If End Sub
Function IsLeapYear(ByVal yr As Integer) As Boolean Dim date1 As Date = CDate("#1/1/" & yr & "#") Dim date2 As Date = CDate("#1/1/" & (yr + 1) & "#") If DateDiff(DateInterval.Day, date1, date2) = 366 Then Return True Else Return False End If End Function
EXERCISES 5.2
1. 88 keys on a piano 5. 1440 minutes in a day 3. You look dashing in blue. 7. Why do clocks run clockwise? Because they were invented in the northern hemisphere where sundials go clockwise. 9. It was the best of times. It was the worst of times. 11. divorced beheaded died divorced beheaded survived 13. 24 blackbirds baked in a pie.
21. There is a parameter in the Sub procedure, but no argument in the statement calling the Sub procedure. 23. Since Handles is a keyword, it cannot be used as the name of a Sub procedure.
25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim num As Integer = 7 Lucky(num) End Sub Sub Lucky(ByVal num As Integer) txtOutput.Text = num & " is a lucky number." End Sub 27. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Tallest("redwood", 362) Tallest("pine", 223) End Sub Sub Tallest(ByVal tree As String, ByVal ht As Double) lstBox.Items.Add("The tallest " & tree & " tree in the U.S. is " & ht & " feet.") End Sub
31. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim num As Double num = CDbl(txtBox.Text) Sum(num) Product(num) End Sub Sub Sum(ByVal num As Double) Dim phrase As String phrase = "The sum of your favorite number with itself is " lstOutput.Items.Add(phrase & (num + num) & ".") End Sub Sub Product(ByVal num As Double) Dim phrase As String phrase = "The product of your favorite number with itself is " lstOutput.Items.Add(phrase & (num * num) & ".") End Sub
33. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click ShowVerse("lamb", "baa") ShowVerse("duck", "quack") ShowVerse("firefly", "blink") End Sub Sub ShowVerse(ByVal animal As String, ByVal sound As String) 'Display a verse from Old McDonald Had a Farm lstOutput.Items.Add("Old McDonald had a farm. Eyi eyi oh.") lstOutput.Items.Add("And on his farm he had a " & animal & ". Eyi eyi oh.") lstOutput.Items.Add("With a " & sound & " " & sound & " here, and a " & sound & " " & sound & " there.") lstOutput.Items.Add("Here a " & sound & ", there a " & sound & ", everywhere a " & sound & " " & sound & ".") lstOutput.Items.Add("Old McDonald had a farm. Eyi eyi oh.") lstOutput.Items.Add("") End Sub
EXERCISES 5.3
1. Gabriel was born in the year 1980. 3. The state flower of Alaska is the Forget Me Not. 5. The first 3 letters of EDUCATION are EDU. 7. Current inventory: 2 is displayed both times the button is clicked. The second click also produces the message "Insufficient inventory, purchase cancelled.") 9. sum = 4 difference = 2 11. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim firstName As String = "" Dim lastName As String = "" Dim salary, newSalary As Double InputData(firstName, lastName, salary) newSalary = RaisedSalary(salary) DisplayOutput(firstName, lastName, newSalary) End Sub Sub InputData(ByRef firstName As String, ByRef lastName As String, ByRef salary As Double) firstName = txtFirstName.Text lastName = txtLastName.Text salary = CDbl(txtCurrentSalary.Text) End Sub Function RaisedSalary(ByVal salary As Double) As Double If salary <= 40000 Then Return 1.05 * salary Else Return salary + 2000 + 0.02 * (salary - 40000) End If End Function Sub DisplayOutput(ByVal ByVal txtOutput.Text = "New " is End Sub firstName As String, ByVal lastName As String, newSalary As Double) salary for " & firstName & " " & lastName & " & FormatCurrency(newSalary) & "."
13. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim annualRateOfInterest, monthlyPayment, begBalance As Double Dim intForMonth, redOfPrincipal, endBalance As Double InputData(annualRateOfInterest, monthlyPayment, begBalance) Calculate(annualRateOfInterest, monthlyPayment, begBalance, intForMonth, redOfPrincipal, endBalance) DisplayData(intForMonth, redOfPrincipal, endBalance) End Sub Sub InputData(ByRef annualRateOfInterest As Double, ByRef monthlyPayment As Double, ByRef begBalance As Double) annualRateOfInterest = CDbl(txtAnnualRateOfInterest.Text) monthlyPayment = CDbl(txtMonthlyPayment.Text) begBalance = CDbl(txtBegBalance.Text) End Sub Sub Calculate(ByVal annualRateOfInterest As Double, ByVal monthlyPayment As Double, ByVal begBalance As Double, ByRef intForMonth As Double, ByRef redOfPrincipal As Double, ByRef endBalance As Double) Dim monthlyRateOfInterest As Double = annualRateOfInterest / 12 intForMonth = (monthlyRateOfInterest / 100) * begBalance redOfPrincipal = monthlyPayment - intForMonth endBalance = begBalance - redOfPrincipal End Sub Sub DisplayData(ByVal intForMonth, ByVal redOfPrincipal, ByVal endBalance) txtIntForMonth.Text = FormatCurrency(intForMonth) txtRedOfPrincipal.Text = FormatCurrency(redOfPrincipal) txtEndBalance.Text = FormatCurrency(endBalance) End Sub
7. Infinite loop. (To end the program, click on the Stop Debugging button on the Toolbar.) 9. Do and Loop are interchanged
15. Until name = "" 17. Until (a <= 1) Or (a >= 3) 19. While n = 0 21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Request and display three names. Dim name As String, num As Integer = 0 Do While num < 3 name = InputBox("Enter a name:") lstOutput.Items.Add(name) num +=1 'Add 1 to value of num. Loop End Sub 11. While num >= 7 13. Until response <> "Y"
25. Private Sub btnLocate_Click(...) Handles btnLocate.Click Dim word As String = "" Dim rPlace, nPlace As Integer Do InputWord(word) rPlace = word.IndexOf("r") nPlace = word.IndexOf("n") If (rPlace = -1) Or (nPlace = -1) Then MessageBox.Show("That word does not contain both r and n.", "") End If Loop Until (rPlace > -1) And (nPlace > -1) ShowFirst(rPlace, nPlace) End Sub
31. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim age As Integer = 1 Do While 1980 + age <> age ^ 2 age += 1 Loop txtOutput.Text = age & " years old" End Sub
33. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim amount As Double = 100 Dim yrs As Integer = 0 Do Until amount < 1 amount = 0.5 * amount yrs += 28 Loop txtOutput.Text = yrs & " years" End Sub 35. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Const INTEREST_PER_MONTH As Double = 0.005 Dim loanAmount As Double = 15000 Dim months As Integer = 0 Dim balance As Double = loanAmount Do Until balance < loanAmount / 2 balance = (1 + INTEREST_PER_MONTH) * balance - 290 months += 1 Loop txtOutput.Text = months & " months" End Sub
37. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim months As Integer = 0 Dim balance As Double = 10000 Do Until balance < 600 balance = 1.003 * balance - 600 months += 1 Loop txtOutput.Text = months & " months; " & FormatCurrency(balance) End Sub
EXERCISES 6.2
1. Pass Pass Pass Pass #1 #2 #3 #4 3. 2 4 6 8 Who do we appreciate? 9. 4 5. 5 6 7
7.
11. The loop is never executed since 25 is greater than 1 and the step is negative. 13. The For ... Next loop will not execute since 20 is greater than 0. You must add Step 1 to the end of the For statement.
15. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click For num As Integer = 1 To 9 Step 2 lstBox.Items.Add(num) Next End Sub 17. Private Sub btndisplay_Click(...) Handles btndisplay.Click For i As Integer = 2 To 100 Step 2 lstOutput.Items.Add(i) Next End Sub
19. Private Sub btnFind_Click(...) Handles btnFind.Click Dim sum As Double = 0, num as Double = 0 For i As Integer = 1 To 5 num = CDbl(InputBox("Enter #" & i)) sum += num Next txtAverage.Text = FormatNumber(sum / 5, 2) End Sub
23. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim value As Double = 20000 For i As Integer = 1 To 5 value = 0.85 * value lstOutput.Items.Add(i & ": " & FormatCurrency(value)) Next End Sub 25. Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim PERCENT_RAISE As Double = 0.05 Dim name As String, age As Integer, salary As Double Dim earnings As Double = 0 name = txtName.Text age = CInt(txtAge.Text) salary = CDbl(txtSalary.Text) For i As Integer = age To 64 earnings += salary salary = salary + (PERCENT_RAISE * salary) Next txtOutput.Text = name & " will earn about " & FormatCurrency(earnings, 0) & "." End Sub
31. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click Const DECAY_RATE As Double = 0.12 Dim grams As Double grams = 10 For yearNum As Integer = 1 To 5 grams = (1 - DECAY_RATE) * grams Next lstOutput.Items.Add("Beginning with 10 grams of cobalt 60,") lstOutput.Items.Add(FormatNumber(grams) & " grams remain after 5 years.") End Sub
35. Private Sub btnAnalyzeOptions_Click(...) Handles btnAnalyzeOptions.Click 'Compare salaries Dim opt1, opt2 As Double opt1 = Option1() opt2 = Option2() lstOutput.Items.Add("Option 1 = " & FormatCurrency(opt1)) lstOutput.Items.Add("Option 2 = " & FormatCurrency(opt2)) If opt1 > opt2 Then lstOutput.Items.Add("Option 1 pays better.") ElseIf opt1 = opt2 lstOutput.Items.Add("Options pay the same. Else lstOutput.Items.Add("Option 2 pays better.") End If End Sub Function Option1() As Double 'Compute the total salary for 10 days, 'with a flat salary of $100/day Dim sum As Integer = 0 For i As Integer = 1 To 10 sum += 100 Next Return sum End Function
Function Option2() As Double 'Compute the total salary for 10 days, 'starting at $1 and doubling each day Dim sum As Integer = 0, daySalary As Integer = 1 For i As Integer = 1 To 10 sum += daySalary daySalary = 2 * daySalary Next Return sum End Function
37. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim dt As Date = CDate("#1/1/" & mtbYear.Text & "#") Dim d As Date For i As Integer = 0 To 11 d = dt.AddMonths(i) lstOutput.Items.Add(FirstTuesday(d)) Next End Sub Function FirstTuesday(ByVal d As Date) As Date For i As Integer = 0 To 6 If FormatDateTime(d.AddDays(i), DateFormat.LongDate).StartsWith("Tuesday") Then Return d.AddDays(i) End If Next End Function
EXERCISES 6.3
1. Mozart 3. Tchaikovsky 5. 3 7. 80 9. 70 11. 300
13. Private Sub btnCount_Click(...) Handles btnCount.Click Dim numWon As Integer = 0 For i As Integer = 0 To lstBox.Items.Count - 1 If CStr(lstBox.Items(i)) = "USC" Then numWon += 1 End If Next txtOutput.Text = CStr(numWon) End Sub
15. Private Sub btnCount_Click(...) Handles btnDetermine.Click Dim college As String = txtCollege.Text txtOutput.Clear() For i As Integer = 0 To lstBox.Items.Count - 1 If CStr(lstBox.Items(i)) = college Then txtOutput.Text = "YES" Exit For End If Next If txtOutput.Text = "" Then txtOutput.Text = "NO" End If End Sub or
17. Private Sub btnReverse_Click(...) Handles btnReverse.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 For i As Integer = highestIndex To 0 Step -1 lstBox2.Items.Add(lstBox.Items(i)) Next End Sub
21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length = 7 Then lstBox2.Items.Add(state) End If Next End Sub
25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim maxLength As Integer = 0 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length > maxLength Then maxLength = state.Length End If Next For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If state.Length = maxLength Then lstBox2.Items.Add(state) End If Next End Sub
27. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim highestIndex As Integer = lstBox.Items.Count - 1 Dim state As String For i As Integer = 0 To highestIndex state = CStr(lstBox.Items(i)) If NumberOfVowels(state) = 4 Then lstBox2.Items.Add(state) End If Next End Sub Function NumberOfVowels(ByVal word As String) As Integer Dim numVowels As Integer = 0 word = word.ToUpper Dim letter As String Dim numLetters As Integer = word.Length For i As Integer = 0 To (numLetters - 1) letter = word.Substring(i, 1) If (letter = "A") Or (letter = "E") Or (letter = "I") Or (letter = "O") Or (letter = "U") Then numVowels += 1 End If Next Return numVowels End Function
31. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click txtOutput.Text = CStr(lstBox.Items(0)) End Sub
35. Private Sub btnRecord_Click(...) Handles btnRecord.Click lstGrades.Items.Add(txtGrade.Text) txtGrade.Clear() txtGrade.Focus() End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sum As Double = 0 Dim minGrade As Double = 100 If lstGrades.Items.Count > 0 Then For i As Integer = 0 To lstGrades.Items.Count - 1 sum += CDbl(lstGrades.Items(i)) If CDbl(lstGrades.Items(i)) < minGrade Then minGrade = CDbl(lstGrades.Items(i)) End If Next Else MessageBox.Show("You must first enter some grades.") End If txtAverage.Text = FormatNumber(sum / lstGrades.Items.Count, 2) txtLowest.Text = CStr(minGrade) End Sub
21. contains a 19th-century date 25. 4 6 2 27. (a) (b) (c) (d) (e) (f) (g) 29. (a) (b) (c) (d) (e) (f) (g) Superior Erie Huron Superior 5 Ontario 3 6.5 0.7 3.5 1.3 6 1.1 3
(last name in alphabetical order) (first name in alphabetical order) (first name in the array) (last name in the array) (number of names in the array) (second name in the array) (first array subscript whose element is Erie)
(greatest population of a New England state) (least population of a New England state) (first population in the array) (last population in the array) (number of numbers in the array) (fourth population in the array) (first array subscript whose element is 1.1)
31. (a) lstOutput.Items.Add(states.First) or lstOutput.Items.Add(states(0)) (b) For i As Integer = 0 To 12 lstOutput.Items.Add(states(i)) Next (c) lstOutput.Items.Add(states.Last) or lstOutput.Items.Add(states(49)) (d) lstOutput.Items.Add(CStr(Array.IndexOf(states, "Ohio") + 1)) (e) lstOutput.Items.Add(states(1)) (f) lstOutput.Items.Add(states(19)) (g) For i As Integer = (states.Count - 9) To (states.Count) lstOutput.Items.Add(states(i - 1)) Next
Logic error. The values of the array elements cannot be altered inside a For Each loop. The output will be 6.
47. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim names() As String = IO.File.ReadAllLines("Names2.txt") Dim dups(names.Count - 1) As String Dim n As Integer = 0 'index for dups For i As Integer = 0 To names.Count - 2 If (names(i + 1) = names(i)) And (Array.IndexOf(dups, names(i)) = -1) Then dups(n) = names(i) n += 1 End If Next If n = 0 Then lstOutput.Items.Add("No duplicates.") Else For i As Integer = 0 To n - 1 lstOutput.Items.Add(dups(i)) Next End If End Sub
51. Function Sum(ByVal nums() As Integer) As Integer Dim total As Integer = 0 For i As Integer = 1 To nums.Count - 1 Step 2 total += nums(i) Next Return total End Function
57. Dim colors() As String = IO.File.ReadAllLines("Colors.txt") Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim letter As String = mtbLetter.Text.ToUpper 'mask L lstColors.Items.Clear() For Each hue As String In SmallerArray(letter) lstColors.Items.Add(hue) Next End Sub Function SmallerArray(ByVal letter As String) As String() Dim smArray(colors.Count - 1) As String Dim counter As Integer = 0 For Each hue As String In colors If hue.StartsWith(letter) Then smArray(counter) = hue counter += 1 End If Next ReDim Preserve smArray(counter - 1) Return smArray End Function
Private Sub btnRecord_Click(...) Handles btnRecord.Click 'Add a score to the array 'If no more room, then display error message. If numGrades >= 100 Then MessageBox.Show("100 scores have been entered.", "No more room.") Else grades(numGrades) = CInt(txtScore.Text) numGrades += 1 lstOutput.Items.Clear() txtScore.Clear() txtScore.Focus() End If End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'Display average of grades and the number of above average grades Dim temp() As Integer = grades ReDim Preserve temp(numGrades - 1) lstOutput.Items.Clear() lstOutput.Items.Add("The average grade is " & FormatNumber(temp.Average, 2) & ".") lstOutput.Items.Add(NumAboveAverage(temp) & " students scored above the average.") End Sub
EXERCISES 7.2
1. 5 7 3. going offer can't 5. 6 7. 103 9. 8
13. 15 12
15. The average after dropping the lowest grade is 80 17. 37 is a prime number 19. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim nums() As Integer = {3, 5, 8, 10, 21} Dim query = From num In nums Where num Mod 2 = 0 Select num txtOutput.Text = query.count & " even numbers" End Sub
21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim dates() As String = IO.File.ReadAllLines("Dates.txt") Dim query = From yr In dates Where (CInt(yr) >= 1800) And (CInt(yr) <= 1899) Select yr If query.Count > 0 Then txtOutput.Text = "contains a 19th century date." Else txtOutput.Text = "does not contains a 19th century date." End If End Sub 23. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim nums() As Integer = {2, 6, 4} Dim query = From num In nums Order By Array.IndexOf(nums, num) Descending For Each num As Integer In query lstOutput.Items.Add(num) Next End Sub
25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim teams() As String = IO.File.ReadAllLines("SBWinners.txt") Dim query = From team In teams Order By team Ascending Distinct For Each team As String In query lstOutput.Items.Add(team) Next End Sub 27. Dim teamNames() As String = IO.File.ReadAllLines("SBWinners.txt") Private Sub btnDetermine_Click(...) Handles btnDetermine.Click 'Display the number of Super Bowls won by the team in the text box Dim query = From team In teamNames Where team.ToUpper = txtName.Text.ToUpper Select team txtNumWon.Text = CStr(query.Count) End Sub
7.2 Exercise 27
7.2 Exercise 29
29. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query1 = From grade In IO.File.ReadAllLines("Final.txt") Select CInt(grade) Dim avg As Double = query1.Average Dim query2 = From grade In IO.File.ReadAllLines("Final.txt") Where CInt(grade) > avg Select grade txtAverage.Text = FormatNumber(avg) txtAboveAve.Text = FormatPercent(query2.Count / query1.Count) End Sub
33. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From pres In IO.File.ReadAllLines("USPres.txt") Let lastName = pres.Split(" "c).Last Order By lastName Select pres For Each pres As String In query lstOutput.Items.Add(pres) Next Distinct End Sub
EXERCISES 7.3
1. The area of a football field is 19200 square yards. 3. Duke was founded in NC in 1838. 7. Joe: 88 Moe: 90 Roe: 95 5. heights are same 170
11. In the event procedure, peace should be prize.peace and yr should be prize.yr. 13. The condition (game1 > game2) is not valid. Structures can only be compared one field at a time. 15. The cities in Texas, along with their populations. The cities are ordered by the sizes of their populations beginning with the most populous city. 17. The population growth of Phoenix from 2000 to 2010.
19. Structure State Dim name As String Dim abbreviation As String Dim area As Double Dim pop As Double End Structure
Dim states() As State Private Sub frmStates_Load(...) Handles MyBase.Load Dim stateRecords() As String = IO.File.ReadAllLines("USStates.txt") Dim n As Integer = stateRecords.Count - 1 ReDim states(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = stateRecords(i) data = line.Split(","c) states(i).name = data(0) states(i).abbreviation = data(1) states(i).area = CDbl(data(2)) states(i).pop = CDbl(data(3)) Next End Sub
7.3 Exercise 19
21.
7.3 Exercise 21
(Begin with the code from Exercise 19 and replace the Click event procedure with the following.)
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From state In states Let density = state.pop / state.area Let formattedDensity = FormatNumber(density, 2) Order By density Descending Select state.name, formattedDensity dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "State" dgvOutput.Columns("formattedDensity").HeaderText = "People per Square Mile" End Sub
29.. (Begin with the code from Exercise 27 and replace the Click event procedure with the following.)
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From person In justices Where person.state = mtbState.Text Let fullName = person.firstName & " " & person.lastName Let yrs = YearsServed(person.yrAppointed, person.yrLeft) Let presLastName = person.apptPres.Split(" "c).Last Select fullName, presLastName, yrs If query.Count = 0 Then MessageBox.Show("No justices appointed from that state.", "NONE") mtbState.Focus() Else dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("fullName").HeaderText = "Justice" dgvOutput.Columns("presLastName").HeaderText = "Appointing President" dgvOutput.Columns("yrs").HeaderText = "Years Served" End If End Sub Function YearsServed(ByVal enter As Double, ByVal leave As Double) As Double If leave = 0 Then Return (Now.Year - enter) Else Return (leave - enter) End If End Function
33. Structure FamousPerson Dim name As String Dim dateOfBirth As Date End Structure
Dim famousPersons() As FamousPerson Private Sub frmFamous_Load(...) Handles MyBase.Load Dim people() As String = IO.File.ReadAllLines("Famous.txt") Dim n As Integer = people.Count - 1 ReDim famousPersons(n) Dim line As String Dim data() As String For i As Integer = 0 To n line = people(i) data = line.Split(","c) famousPersons(i).name = data(0) famousPersons(i).dateOfBirth = CDate(data(1)) Next End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From person In famousPersons Where (person.dateOfBirth >= #1/1/1970#) And (person.dateOfBirth < #1/1/1980#) Select person.name lstOutput.DataSource = query.ToList lstOutput.SelectedItem = Nothing End Sub
35. Dim people() As Person Private Sub frmFamous_Load(...) Handles MyBase.Load 'Place the data for each person into the array people. Dim group() As String = IO.File.ReadAllLines("Famous.txt") Dim n As Integer = group.Count - 1 ReDim people(n) Dim data() As String For i As Integer = 0 To n data = group(i).Split(","c) people(i).name = data(0) people(i).dateOfBirth = CDate(data(1)) Next End Sub
Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From individual In people Let ageInDays = FormatNumber(DateDiff(DateInterval.Day, individual.dateOfBirth, Today), 0) Let dayOfBirth = DayOfWeek(individual.dateOfBirth) Where individual.dateOfBirth.AddYears(40) <= Today And individual.dateOfBirth.AddYears(50) > Today Select individual.name, ageInDays, dayOfBirth dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing End Sub Function DayOfWeek(ByVal d As Date) As String Dim d1 As String = FormatDateTime(d, DateFormat.LongDate) Dim d2() As String = d1.Split(","c) Return First End Function
37. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click lstOutput.Items.Clear() For i As Integer = 0 To club.Count - 1 If club(i).courses.Count = 3 Then lstOutput.Items.Add(club(i).name) End If Next End Sub
EXERCISES 7.4
1. 1 3. 3 5. 55 7. 14 9. 2 11. 55
13. Dim twice(2, 3) As Double For r As Integer = 0 To 2 For c As Integer = 0 To 3 twice(r, c) = 2 * nums(r, c) Next Next 15 'use a For Each loop Dim total As Double = 0 For Each num As Double In nums If num Mod 2 = 0 Then total += num End If Next lstOutput.Items.Add(total) 'use LINQ Dim query = From num In nums.Cast(Of Double)() Where (num Mod 2 = 0) Select num lstOutput.Items.Add(query.Sum)
17. 12
Private Sub btnAdd_Click(...) Handles btnAdd.Click If (count = 15) Then MessageBox.Show("Fifteen students already stored.", "Warning") Else count += 1 names(count - 1) = txtName.Text scores(count - 1, 0) = CInt(txtExam1.Text) scores(count - 1, 1) = CInt(txtExam2.Text) scores(count - 1, 2) = CInt(txtExam3.Text) scores(count - 1, 3) = CInt(txtExam4.Text) scores(count - 1, 4) = CInt(txtExam5.Text) 'Reset input txtName.Clear() txtExam1.Clear() txtExam2.Clear() txtExam3.Clear() txtExam4.Clear() txtExam5.Clear() txtName.Focus() End If End Sub
7. The new file contains the full names of the justices whose last name begins with the letter B and the years they were appointed to the court. The justices are ordered by the year they were appointed. 9. The new file is the same as the original file except that the last three fields have been deleted from each record. 11. The new file contains the names of the people who subscribe to either the New York Times or the Wall Street Journal, or both. 13. The new file contains the names of the people who subscribe to the New York Times but not the Wall Street Journal.
15. Private Sub btnBoth_Click(...) Handles btnBoth.Click 'Create a file of presidents who were also vice presidents Dim vicePres() As String = IO.File.ReadAllLines("VPres.txt") Dim presidents() As String = IO.File.ReadAllLines("USPres.txt") Dim both() As String = presidents.Intersect(vicePres).ToArray IO.File.WriteAllLines("Both.txt", both) MessageBox.Show(both.Count & " presidents", "File Created") End Sub
17. Private Sub btnXor_Click(...) Handles btnXor.Click 'Create a file of people who were pres or VP but not both Dim vicePres() As String = IO.File.ReadAllLines("VPres.txt") Dim presidents() As String = IO.File.ReadAllLines("USPres.txt") Dim eitherOr() As String = presidents.Union(vicePres).ToArray Dim both() As String = presidents.Intersect(vicePres).ToArray Dim exclusiveOr() As String = eitherOr.Except(both).ToArray IO.File.WriteAllLines("Xor.txt", exclusiveOr) MessageBox.Show(exclusiveOr.Count & " presidents or vice presidents, but not both", "File Created") End Sub
21. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim cities() As String = IO.File.ReadAllLines("Cities.txt") Dim query = From city In cities Let data = city.Split(","c) Let pop2010 = CDbl(data(3)) Order By pop2010 Descending Select pop2010 Dim pops() As Double = query.ToArray ReDim Preserve pops(9) txtOutput.Text = FormatNumber(100000 * pops.Sum, 0) End Sub
25. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim states() As String = IO.File.ReadAllLines("USStates.txt") Dim query1 = From line In states Let area = CInt(line.Split(","c)(2)) Select area Dim totalArea = query1.Sum Dim query2 = From line In states Let name = line.Split(","c)(0) Let area = CInt(line.Split(","c)(2)) Let percentArea = FormatPercent(area / totalArea) Order By area Descending Select name, percentArea dgvOutput.DataSource = query2.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "State" dgvOutput.Columns("percentArea").HeaderText = "Percentage of Total Area" End Sub
29. Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Dim query = From justice In justices Let data = justice.Split(","c) Let firstName = data(0) Let secondName = data(1) Let pres = data(2) Let yrAppt = data(4) Let yrLeft = data(5) Select firstName & "," & secondName & "," & pres & "," & yrAppt & "," & yrLeft IO.File.WriteAllLines("JusticesNoState.txt", query) End Sub 31. Private Sub btnCreate_Click(...) Handles btnDisplay.Click 'query1: all states; query2: states with justices Dim states() As String = IO.File.ReadAllLines("USStates.txt") Dim justices() As String = IO.File.ReadAllLines("Justices.txt") Dim query1 = From state In states Let abbrev = state.Split(","c)(1) Select abbrev Dim query2 = From justice In justices Let state = justice.Split(","c)(3) Select state IO.File.WriteAllLines("NoJustices.txt", query1.Except(query2)) End Sub
EXERCISES 8.2
1. Hello 3. Bon Jour 5. You must enter a number.
7. Error occurred.
11. The file Welcome.txt is created and has the following lines:
Hello Bon Jour
13. The filespec Greetings.txt should be delimited with quotation marks. 15. There should be no quotations around the variable name as the argument to the CreateText method. 17. The variable age is declared within the Try-Catch-Finally block. Therefore it has block-level scope and is not available below the line End Try.
19. Private Sub btnCreate_Click(...) Handles btnCreate.Click 'Create a text file and populate it Dim sw As IO.StreamWriter = IO.File.CreateText("Cowboy.txt") sw.WriteLine("Colt Peacemaker,12.20") sw.WriteLine("Holster,2.00") sw.WriteLine("Levi Strauss jeans,1.35") sw.WriteLine("Saddle,40.00") sw.WriteLine("Stetson,10.00") sw.Close() 'Always close the writer when finished. MessageBox.Show("The file has been created.", "Done") End Sub
21. Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Append item to a text file Dim sw As IO.StreamWriter = IO.File.AppendText("Cowboy.txt") sw.WriteLine("Winchester Rifle,20.50") sw.Close() MessageBox.Show("The item has been added to the file.", "DONE") End Sub
27. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim counter As Integer = 0 Dim num As Double Do Until sr.EndOfStream num = CDbl(sr.ReadLine) counter += 1 Loop txtOutput.Text = CStr(counter) sr.Close() End Sub
31. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim sr As IO.StreamReader = IO.File.OpenText("Numbers.txt") Dim counter As Integer = 0 Dim total As Double = 0 Dim num As Double Do Until sr.EndOfStream num = CDbl(sr.ReadLine) counter += 1 total += num Loop txtOutput.Text = FormatNumber(total / counter) sr.Close() End Sub
EXERCISES 8.3 1. No 3. No 5. No 7. No 9. No
11. <?xml version='1.0'?> <!-- This file contains the ages of the presidents when inaugurated.--> <Presidents> <president> <name>George Washington</name> <ageAtInauguation>57</ageAtInauguation> </president> <president> <name>John Adams</name> <ageAtInauguation>61</ageAtInauguation> </president> </Presidents> 13. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim query = From st In stateData.Descendants("state") Let pop = CInt(st.<population>.Value) Select pop txtOutput.Text = FormatNumber(query.Sum, 0) End Sub
15. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim queryPop = From st In stateData.Descendants("state") Let pop = CInt(st.<population>.Value) Select pop Dim queryArea = From st In stateData.Descendants("state") Let area = CInt(st.<area>.Value) Select area txtOutput.Text = FormatNumber(queryPop.Sum / queryArea.Sum) & " people per square mile" End Sub
19. Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim stateData As XElement = XElement.Load("USStates.xml") Dim query1 = From st In stateData.Descendants("state") Let name = st.<name>.Value Let numVowels = NumberOfVowels(name) Order By numVowels Descending Select numVowels Dim maxVowels As Integer = query1.First Dim query2 = From st In stateData.Descendants("state") Let name = st.<name>.Value Where NumberOfVowels(name) = maxVowels Select name lstOutput.DataSource = query2.ToList lstOutput.SelectedItem = Nothing End Sub
25(b). Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim senateData As XElement = XElement.Load("Senate111.XML") Dim query = From st In senateData.Descendants("senator") Let name = st.<name>.Value Let state = st.<state>.Value Let party = st.<party>.Value Order By state, name Ascending Select name, state, party dgvSenators.DataSource = query.ToList dgvSenators.CurrentCell = Nothing dgvSenators.Columns("name").HeaderText = "Senator" dgvSenators.Columns("state").HeaderText = "State" dgvSenators.Columns("party").HeaderText = "Party Affiliation" End Sub
Chopin is deleted from the list. The currently selected item in lstBox, Mozart, is deleted. The item Haydn is inserted into lstBox between Chopin and Mozart. The names in the list box will appear in descending alphabetical order.
cboBox.Text = "Dante"
11. cboBox.Items.Remove("Shakespeare") 13. cboBox.Items.RemoveAt(cboBox.Items.Count - 1) 15. Dim i As Integer = 0 Do While i < cboBox.Items.Count If CStr(cboBox.Items(i)).Substring(0, 1) = "M" Then cboBox.Items.RemoveAt(i) Else i += 1 End If Loop
9.1 Exercise 23
25. 'Note: This event procedure handles events from all three combo boxes Private Sub SelectedIndexChanged(...) Handles _ cboBrand.SelectedIndexChanged, cboMemory.SelectedIndexChanged, cboMonitor.SelectedIndexChanged 'Update output if all choices have been made. If (cboBrand.SelectedIndex >= 0) And (cboMemory.SelectedIndex >= 0) And (cboMonitor.SelectedIndex >= 0) Then txtOutput.Text = "You have a " & cboBrand.Text & " computer with " & cboMemory.Text & " of memory and a " & cboMonitor.Text & " monitor." End If End Sub
EXERCISES 9.2 1. The Tick event will be triggered every 5 seconds (5000 milliseconds). 3. The tooltip will appear one second after the cursor is hovered over a control. 5. A check mark appears in front of the mnuOrderAsc menu item. 7. The Tick event will be triggered every intVar seconds. 9. The name of one of the 44 U.S. presidents is selected at random and displayed in txtBox. 11. Two states are selected at random and displayed in the list box. 13. The contents of the Clipboard are deleted. 15. The text currently selected in txtBox, if any, is copied into the Clipboard. 17. The contents of the Clipboard are displayed in txtBox. 19. The contents of the Clipboard are assigned to the variable strVar. 21. A blue circle of radius 50 pixels will be drawn in the picture box. Its upper- leftmost point will be 20 pixels from the left side of the picture box and 30 pixels from the top side. 23. A picture of an airplane will be placed in the picture box. 25. Clicking on the arrow on either end of the scroll bar will move the button the same ("large") distance as clicking on the bar between the scroll box and an arrow.
27. Timer1.Enabled = False 29. Dim randomNum As New Random() txtBox.Text = CStr(randomNum.Next(1, 13)) 31. Dim sr As IO.StreamReader = IO.Files.ReadText("Towns.txt") Dim randomNum As New Random() Dim num As Integer = randomNum.Next(1, 26) Dim city As String For i As Integer = 1 To num city = sr.ReadLine Next txtBox.Text = city
35. Clipboard.SetText("")
37. Clipboard.SetText(txtBox.SelectedText)
39. Dim amount As Integer amount = CInt(Clipboard.GetText) 41. mnuOrderDesc.Checked = False 43. VScrollBar2.Value = VScrollBar2.Minimum
45. The menu item mnuOrderAsc is grayed out and cannot be selected.
51. Dim randomNum As New Random() Private Sub btnPlay_Click(...) Handles btnPlay.Click 'Roll a pair of dice until 7 appears 1000 times. Dim die1, die2 As Integer Dim numberOfSevens As Integer = 0 Dim numberOfRolls As Integer = 0 Do 'Roll the dice die1 = randomNum.Next(1, 7) die2 = randomNum.Next(1, 7) 'If lucky 7, increment the sevens counter. If (die1 + die2) = 7 Then numberOfSevens += 1 End If numberOfRolls += 1 'Increment the rolls counter. Loop Until (numberOfSevens = 1000) 'Display the result to two decimal places. txtOutput.Text = FormatNumber(numberOfRolls / numberOfSevens, 2) End Sub
55.
59. Private Sub tmrMoon_Tick(...) Handles tmrMoon.Tick 'Update the phase and display the image. 'Timer Interval setting is 2000; Timer Enabled setting is True phase += 1 If phase = 9 Then phase = 1 End If picBox.Image = Image.FromFile("Moon" & phase & ".bmp") End Sub
EXERCISES 9.3
1. $106.00 3. Your last name begins with K. 5. 'Form1's code Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Form2.ShowDialog() txtQuotation.Text = Form2.quotation End Sub 'Form2's code (Movies) Public quotation As String Private Sub btnProcessSelection_Click(...) Handles _ btnProcessSelection.Click If rad1.Checked Then quotation = "Plastics." End If If rad2.Checked Then quotation = "Rosebud." End If If rad3.Checked Then quotation = "That's all folks." End If Me.Close() End Sub
EXERCISES 9.4
1. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim gr As Graphics = picBox.CreateGraphics Dim x As Double = picBox.Width / 2 Dim y As Double = picBox.Height / 2 Dim r As Double = x / 2 If r > y / 2 Then r = y / 2 End If gr.FillEllipse(Brushes.Black, CSng(x - r), CSng(y - r), CSng(2 * r), CSng(2 * r)) End Sub
3. Private Sub btnDraw_Click(...) Handles btnDraw.Click Dim gr As Graphics = picBox.CreateGraphics Dim x As Double = picBox.Width / 2 Dim y As Double = picBox.Height / 2 Dim r As Double = 20 gr.FillEllipse(Brushes.Red, CSng(x - r), CSng(y - r), CSng(2 * r), CSng(2 * r)) r = 19 gr.FillEllipse(Brushes.White, CSng(x - r), CSng(y - r), CSng(2 * r), CSng(2 * r)) End Sub
7. Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim gr As Graphics = picFlag.CreateGraphics Dim br() As Brush = {Brushes.Orange, Brushes.White, Brushes.Green} Dim r As Integer = 12 'radius of circle 'picFlag.Width = 149; picFlag.Height = 99 For i As Integer = 0 To 2 gr.FillRectangle(br(i), 0, 0 + i * 33, 149, 33) Next gr.FillPie(Brushes.Orange, 75 - r, 49 - r, 2 * r, 2 * r, 0, 360) gr.DrawLine(Pens.Black, 0, 0, 148, 0) 'top border gr.DrawLine(Pens.Black, 0, 0, 0, 98) 'left border gr.DrawLine(Pens.Black, 0, 98, 148, 98) 'bottom border gr.DrawLine(Pens.Black, 148, 0, 148, 98) 'right border End Sub
Private Sub PrintDocument1_PrintPage...) Handles _ PrintDocument1.PrintPage Dim gr As Graphics = e.Graphics Dim br() As Brush = {Brushes.Green, Brushes.White, Brushes.Red} For i As Integer = 0 To 2 gr.FillRectangle(br(i), 300 + i * 50, 200, 50, 99) Next gr.DrawLine(Pens.Black, 300, 200, 448, 200) 'top border gr.DrawLine(Pens.Black, 300, 200, 300, 298) 'left border gr.DrawLine(Pens.Black, 300, 298, 448, 298) 'bottom border gr.DrawLine(Pens.Black, 448, 200, 448, 298) 'right border End Sub Private Sub btnPreview_Click(...) Handles btnPreview.Click PrintPreviewDialog1.Document = PrintDocument1 PrintPreviewDialog1.ShowDialog() End Sub
7. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query = From city In MegacitiesDataSet.Cities Let popGrowth = (city.pop2015 - city.pop2010) / city.pop2010 Let formattedPopGrowth = FormatPercent(popGrowth) Order By popGrowth Descending Select city.name, city.country, formattedPopGrowth dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "City" dgvOutput.Columns("country").HeaderText = "Country" dgvOutput.Columns("formattedPopGrowth").HeaderText = "Projected Population Growth" End Sub
11. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim query1 = From city In MegacitiesDataSet.Cities Let perIncr = (city.pop2015 - city.pop2010) / city.pop2010 Order By perIncr Descending Select city.name Dim geatestCity As String = query1.First Dim query2 = From city In MegacitiesDataSet.Cities Where city.name = geatestCity Select city.name, city.country, city.pop2010, city.pop2015 dgvOutput.DataSource = query2.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "City" dgvOutput.Columns("country").HeaderText = "Country" dgvOutput.Columns("pop2010").HeaderText = "Population in 2010" dgvOutput.Columns("pop2015").HeaderText = "Population in 2015" End Sub
13. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CountriesTableAdapter.Fill(Me.MegacitiesDataSet.Countries) Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) Dim query = From city In MegacitiesDataSet.Cities Select city.name lstCities.DataSource = query.ToList End Sub Private Sub lstCities_SelectedIndexChanged(...) Handles _ lstCities.SelectedIndexChanged Dim query = From city In MegacitiesDataSet.Cities Join country In MegacitiesDataSet.Countries On city.country Equals country.name Let cityPer = city.pop2010 / country.pop2010 Where city.name = lstCities.Text Select cityPer txtOutput.Text = FormatPercent(query.First) End Sub
15. Private Sub frmCities_Load(...) Handles MyBase.Load Me.CitiesTableAdapter.Fill(Me.MegacitiesDataSet.Cities) End Sub Private Sub btnCreate_Click(...) Handles btnCreate.Click Dim query = From city In MegacitiesDataSet.Cities Select city.name & "," & city.country & "," & city.pop2010 & "," & city.pop2015 IO.File.WriteAllLines("MEGACITIES.TXT", query.ToArray) MessageBox.Show("File Created") End Sub
23. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Dim query = From team In BaseballDataSet.Teams Order By team.name Select team.name lstTeams.DataSource = query.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(...) Handles _ lstTeams.SelectedIndexChanged Dim query = From team In BaseballDataSet.Teams Where team.name = lstTeams.Text Select team.stadium txtStadium.Text = query.First End Sub
27. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) Dim query = From team In BaseballDataSet.Teams Order By team.name Select team.name lstTeams.DataSource = query.ToList End Sub Private Sub lstTeams_SelectedIndexChanged(...) Handles _ lstTeams.SelectedIndexChanged Dim query = From player In BaseballDataSet.Players Where player.team = lstTeams.Text Let battingAve = player.hits / player.atBats Let formattedBattingAve = FormatNumber(battingAve, 3) Order By battingAve Descending Select player.name, formattedBattingAve dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Name" dgvOutput.Columns("formattedBattingAve").HeaderText = "Batting Average" End Sub
29. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) End Sub Private Sub radAmerican_CheckedChanged(...) Handles radAmerican.CheckedChanged DisplayPlayers("American") End Sub Private Sub radNational_CheckedChanged(...) Handles radNational.CheckedChanged DisplayPlayers("National") End Sub Sub DisplayPlayers(ByVal group As String) Dim query = From team In BaseballDataSet.Teams Let battingAve = team.hits / team.atBats Let formattedBattingAve = FormatNumber(battingAve, 3) Where team.league = group Order By battingAve Descending Select team.name, formattedBattingAve dgvOutput.DataSource = query.ToList dgvOutput.CurrentCell = Nothing dgvOutput.Columns("name").HeaderText = "Team" dgvOutput.Columns("formattedBattingAve").HeaderText = "Batting Average" End Sub
31. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) End Sub Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim query1 = From team In BaseballDataSet.Teams Where team.league = "American" Select team.hits Dim query2 = From team In BaseballDataSet.Teams Where team.league = "American" Select team.atBats txtBattingAve.Text = FormatNumber(query1.Sum / query2.Sum, 3) End Sub
33. Private Sub frmBaseball_Load(...) Handles MyBase.Load Me.TeamsTableAdapter.Fill(Me.BaseballDataSet.Teams) Me.PlayersTableAdapter.Fill(Me.BaseballDataSet.Players) End Sub Private Sub btnCount_Click(...) Handles btnCount.Click Dim query = From player In BaseballDataSet.Players Join team In BaseballDataSet.Teams On player.team Equals team.name Where team.league = "National" Select player.name txtNational.Text = FormatNumber(query.Count, 0) End Sub
39.
film
EXERCISES 10.2 7. Add a record to the Cities table whose name field is empty or contains the same name as an already existing record.
9. (BindingSource1.Find("name", strVar) = 0) And (strVar <> "Bombay")
11. Create a control named BindingSource2 that has the Countries table as its DataMember.
Private Sub CountryTextBox_Leave(...) Handles _ CountryTextBox.Leave, BindingNavigator1.Click BindingSource2.Position = BindingSource2.Find("name", CountryTextBox.Text) If (CountryTextBox.Text <> "") And (BindingSource2.Position = 0) And (CountryTextBox.Text <> "Argentina") Then MessageBox.Show("Not a valid country.", "ERROR") CountryTextBox.Focus() End If End Sub 13. Private Sub frmMovies_Load(...) Handles MyBase.Load Me.LinesTableAdapter.Fill(Me.MoviesDataSet.Lines) End Sub Private Sub btnUpdate_Click(...) Handles btnUpdate.Click 'These two lines update the database file on the hard drive. BindingSource1.EndEdit() LinesTableAdapter.Update(MoviesDataSet.Lines) End Sub
17. Apollo 13 does not appear in the key field of the Actors table. Thus the Rule of Referential Integrity would be violated. 19. Replace the table with two tables. The first table should contain the fields name, address, and city. The second table should contain the fields city, state, and stateCapital. 21. Write a program similar to the one in Example 1, but using the database Justices accdb. Then use the program to update the database.
CHAPTER 11 EXERCISES 11.1 1. Any negative grade will be recorded as 0 and any grade greater than 100 will be recorded as 100. 3. Remove the keyword WriteOnly from the Midterm property block and add the following Get property procedure to it:
Get Return m_midterm End Get
5. The properties Midterm and Final are write only. 7. The property SocSecNum is initialized to the value 999-99-9999. 9. The keyword New is missing from the third line of the event procedure. 11. The statement nom = m_name is not valid. m_name would need to be Public and referred to by scholar.m_name. 13. The statements pupil.Midterm = scholar.Midterm and lstGrades.Items.Add(pupil.Midterm) are not valid. The Midterm property is write only; it can be set, but cannot return a value.
15. Country: Canada Capital: Ottawa Pop: 31 million
Student Solutions Manual (Page 166 of 211) 17. Change 20 to 20 in the btnMove_Click event procedure, and create a frmCircle_Load event procedure with the following lines,
round.Xcoord = picCircle.Width - 40 round.Ycoord = picCircle.Height - 40
EXERCISES 11.2
1. Sub btnDisplay_Click(...) Handles btnDisplay.Click ReDim Preserve students(lastStudentAdded) Dim query = From pupil In students Let name = pupil.Name Let ssn = pupil.SocSecNum Let semGrade = pupil.CalcSemGrade Where semGrade = "A" Select pupil.Name, pupil.SocSecNum, pupil.CalcSemGrade dgvGrades.DataSource = query.ToList dgvGrades.CurrentCell = Nothing dgvGrades.Columns("Name").HeaderText = "Student Name" dgvGrades.Columns("SocSecNum").HeaderText = "SSN" dgvGrades.Columns("CalcSemGrade").HeaderText = "Grade" ReDim Preserve students(50) txtName.Focus() End Sub
Public ReadOnly Property Entered() As Date Get Return m_entered End Get End Property Public ReadOnly Property Area() As Double Get Return m_area End Get End Property Public Property Population() As Double Sub New(ByVal n As String, ByVal a As String, ByVal e As Date, ByVal ar As Double, ByVal p As Double) 'Store parameters into member variables m_name = n m_abbr = a m_entered = e m_area = ar _Population = p End Sub Function Density() As Double 'Density is calculated as population divided by area. Return _Population / m_area End Function End Class 'State
7. Public Class frmCashRegister Dim WithEvents register As New CashRegister() Private Sub btnAdd_Click(...) Handles btnAdd.Click 'Add an amount to the balance. register.Add(CDbl(txtAmount.Text)) txtBalance.Text = FormatCurrency(register.Balance) txtAmount.Clear() txtAmount.Focus() End Sub
Private Sub btnResult_Click(...) Handles btnResult.Click 'Add the x and y fractions to get the z fraction. 'Store the input into the x and y fractions. x.Num = CInt(txtNumX.Text) x.Den = CInt(txtDenX.Text) y.Num = CInt(txtNumY.Text) y.Den = CInt(txtDenY.Text) 'Add the two fractions. z.Num = (x.Num * y.Den) + (y.Num * x.Den) z.Den = x.Den * y.Den 'Reduce and display the result. z.Reduce() txtNumZ.Text = CStr(z.Num) txtDenZ.Text = CStr(z.Den) End Sub Sub fraction_ZeroDenominator() Handles x.ZeroDenominator, _ y.ZeroDenominator 'If x or y has a zero denominator, display an error message. Dim message As String = "You cannot set a denominator to zero. " & "All such denominators will be replaced by 1." MessageBox.Show(message) If txtDenX.Text = "0" Then txtDenX.Text = CStr(1) x.Den = 1 End If If txtDenY.Text = "0" Then txtDenY.Text = CStr(1) y.Den = 1 End If End Sub End Class 'frmAdd
Public Event ZeroDenominator() Public Property Num() As Double Public Property Den() As Double Get Return m_den End Get Set(ByVal Value As Double) 'Raise the event if zero If Value = 0 Then RaiseEvent ZeroDenominator() Else m_den = Value End If End Set End Property Sub Reduce() Dim t As Double Dim m As Double = Num Dim n As Double = m_den 'Algorithm to calculate greatest common divisor of m and n. 'After the loop terminates, the value of m will be the GCD. Do While (n <> 0) t = n n = m Mod n m = t Loop 'Divide both numerator and denominator by greatest common divisor. If m <> 0 Then Num = Num / m m_den = m_den / m End If End Sub End Class 'Fraction
Public Sub New() m_first = New PairOfDice() 'The time is used to determine how the sequence of random numbers 'will be generated. The For...Next loop below guarantees that the 'two random number generators will act differently. Without the 'For...Next loop, often the two rolls will be identical. For i As Integer = 1 To 10000000 Next Second = New PairOfDice() End Sub Public ReadOnly Property First() As PairOfDice Get Return m_first End Get End Property Public Property Second() As PairOfDice Get Return m_second End Get Set(ByVal value As PairOfDice) m_second = value End Set End Property
Public Property Name() As String Public Property Hours() As Double Get Return m_hours End Get Set(ByVal Value As Double) m_hours = Value 'Update the tax property also tax.Wages = m_hours * m_salary End Set End Property
Function FICA() As Double 'Calculate Social Security benefits tax and Medicare tax 'for a single pay period in 2009 Dim socialSecurityBenTax, medicare As Double If (YearToDate + Wages) <= 106800 Then socialSecurityBenTax = 0.062 * Wages ElseIf YearToDate < 106800 Then socialSecurityBenTax = 0.062 * (106800 - YearToDate) End If medicare = 0.0145 * Wages 'Return the sum Return socialSecurityBenTax + medicare End Function Function Withholding() As Double Dim adjPay As Double = Wages - (70.19 * Withhold) 'Subtract exemptions If Married Then Select Case adjPay Case Is <= 303 Return 0 Case Is <= 470 Return (adjPay - 303) * 0.1 Case Is <= 1455 Return (adjPay - 470) * 0.15 + 16.7 Case Is <= 2272 Return ((adjPay - 1455) * 0.25) + 163.45 Case Is <= 4165 Return ((adjPay - 2272) * 0.28) + 368.7 Case Is <= 7021 Return ((adjPay - 4165) * 0.33) + 898.74 Case Else Return ((adjPay - 7321) * 0.35) + 1940.22 End Select
7. The keyword Overrides should be Inherits. 9. The Hi function should be declared with the Overridable keyword in class Hello and with the keyword Overrides keyword in class Aussie. 11. The Hi function should be declared with the Overrides keyword in class Cowboy. 13. The Hello class should be declared with the MustInherit keyword, and the function Hi should be declared with the MustOverride keyword. 15. The Hello class should be declared with the MustInherit keyword, not MustOverride.
17. Public Class frmCalculator 'Create the machines Dim adder As New AddingMachine() Dim calc As New Calculator() Dim sci As New ScientificCalculator() Private Sub radAddingMachine_CheckedChanged(...) Handles _ radAddingMachine.CheckedChanged 'Hide the multiply, divide and exponentiation 'functionality if checked If radAddingMachine.Checked Then btnMultiply.Visible = False btnDivide.Visible = False btnExponentiation.Visible = False End If End Sub Private Sub radCalculator_CheckedChanged(...) Handles _ radCalculator.CheckedChanged 'Show the multiply and divide functionality, 'hide the exponentiation if checked If radCalculator.Checked Then btnMultiply.Visible = True btnDivide.Visible = True btnExponentiation.Visible = False End If End Sub
Sub ProcessTruck() m_count += 1 'Process a truck: $2.00 Deposit(2) End Sub End Class 'FastTrackRegister
11.3 Exercise 21
21. Public Class frmBookstore Dim books(10) As Book Dim count As Integer 'Stores books 'Last stored book
Private Sub btnOrder_Click(...) Handles btnOrder.Click 'Create appropriate book object Dim book As Book If radTextbook.Checked Then book = New Textbook() Else book = New Tradebook() End If 'Store the values into the book object book.Name = txtName.Text book.Cost = CDbl(txtCost.Text) book.Quantity = CInt(txtQuantity.Text) 'Increment counter and store book into array books(count) = book count += 1 'Reset input fields and focus on the quantity txtName.Clear() txtCost.Clear() txtQuantity.Text = "" txtQuantity.Focus() End Sub
13. Protected Sub btnReverse_Click(...) Handles btnReverse.Click txtBackwards.Text = Reverse(txtWord.Text) End Sub Function Reverse(ByVal info As String) As String Dim m As Integer, temp As String = "" m = info.Length For j As Integer = m - 1 To 0 Step -1 temp &= info.Substring(j, 1) Next Return temp End Function
17. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim states() As String = IO.File.ReadAllLines(MapPath("App_Data\States.txt")) For Each state As String In states If state.EndsWith("ia") Then lstOutput.Items.Add(state) End If Next End Sub
19. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim states() As String = IO.File.ReadAllLines(MapPath("App_Data\States.txt")) Dim letter As String = txtLetter.Text lstOutput.Items.Clear() For Each state As String In states If state.StartsWith(letter) Then lstOutput.Items.Add(state) End If Next End Sub
EXERCISES 12.2
1. Protected Sub Page_Load(...) Handles Me.Load If Not IsPostBack Then Dim states() As String = IO.File.ReadAllLines(MapPath("App_Data\States.txt")) Dim query = From state In states Order By state Select state lstStates.DataSource = query lstStates.DataBind() txtNumStates.Text = CStr(lstStates.Items.Count) End If End Sub Protected Sub btnDelete_Click(...) Handles btnDelete.Click lstStates.Items.Remove(lstStates.Text) txtNumStates.Text = CStr(lstStates.Items.Count) End Sub
12.2 Exercise 1
3. 'Note: The AutoPostBack and CausesValidation properties were 'set to True for each check box. Protected Sub rblModel_SelectedIndexChanged(...) Handles _ rblModel.SelectedIndexChanged, chkUpgradedVideo.CheckedChanged, chkModem.CheckedChanged, chkMemory.CheckedChanged Dim cost As Double = 0 'Add amounts to the cost based upon selections. If rblModel.Text = "Deluxe" Then cost += 1000 Else cost += 1500 End If If chkUpgradedVideo.Checked Then cost += 200 End If If chkModem.Checked Then cost += 30 End If If chkMemory.Checked Then cost += 120 End If txtOutput.Text = FormatCurrency(cost) End Sub
5. Protected Sub btnConvert_Click(...) Handles btnConvert.Click Dim fahrenheitTemp, celsiusTemp As Double fahrenheitTemp = CDbl(txtTempF.Text) celsiusTemp = FtoC(fahrenheitTemp) txtTempC.Text = CStr(celsiusTemp) End Sub Function FtoC(ByVal t As Double) As Double Return (5 / 9) * (t - 32) End Function
EXERCISES 12.3
1. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.Cities Order By city.name Descending Select city.name, city.pop2010 chtMegacities.DataBindTable(query, "name") chtMegacities.ChartAreas(0).AxisX.Interval = 1 chtMegacities.ChartAreas(0).AxisX.Title = "City" chtMegacities.ChartAreas(0).AxisY.Title = "2010 Population in Millions " End Sub
3. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.Cities Let popGrowth = 100 * (city.pop2015 - city.pop2010) / city.pop2010 Order By popGrowth Descending Select city.name, popGrowth chtMegacities.DataBindTable(query, "name") chtMegacities.ChartAreas(0).AxisX.Interval = 1 chtMegacities.ChartAreas(0).AxisX.Title = "City" chtMegacities.ChartAreas(0).AxisY.Title = "Percentage Population Growth" End Sub
7. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim mcDC As New MegacitiesDataContext Dim query = From city In mcDC.Cities Join country In mcDC.Countries On city.country Equals country.name Select city.name, country.pop2010 chtMegacities.DataBindTable(query, "name") chtMegacities.ChartAreas(0).AxisX.Interval = 1 chtMegacities.ChartAreas(0).AxisX.Title = "City" chtMegacities.ChartAreas(0).AxisY.Title = "2010 Pop. of Country in Millions" End Sub
13. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim mcDC As New MegacitiesDataContext Dim query = From country In mcDC.Countries Let pop = 1000000 * country.pop2010 Let formattedPop = FormatNumber(pop, 0) Order By pop Descending Select country.name, formattedPop GridView1.DataSource = query GridView1.DataBind() GridView1.HeaderRow.Cells(0).Text = "Country" GridView1.HeaderRow.Cells(1).Text = "Population in 2010" End Sub
17. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.Pizzerias Order By chain.sales2008 Descending Let amount = chain.sales2008 / 1000000 Select chain.name, amount chtPizzaChains.DataBindTable(query, "name") chtPizzaChains.ChartAreas(0).AxisX.Interval = 1 chtPizzaChains.ChartAreas(0).AxisX.Title = "Pizzeria" chtPizzaChains.ChartAreas(0).AxisY.Title = "2008 Sales in Billions" End Sub
21. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.Pizzerias Order By chain.name Let sales2007 = chain.sales2007 / 1000000 Let sales2008 = chain.sales2008 / 1000000 Select chain.name, sales2007, sales2008 chtPizzaChains.DataBindTable(query, "name") chtPizzaChains.ChartAreas(0).AxisX.Interval = 1 chtPizzaChains.ChartAreas(0).AxisX.Title = "Pizzeria" chtPizzaChains.ChartAreas(0).AxisY.Title = "2007 & 2008 Sales in $Billion" End Sub
25. Protected Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim pizzaDC As New PizzaDataContext Dim query = From chain In pizzaDC.Pizzerias Select chain.numStores2008 txtOutput.Text = FormatNumber(query.Sum, 0) End Sub