Chapter 6: Using VB.NET Supplied Classes Visual Basic.NET Programming: From Problem Analysis to Program Design
Visual Basic.NET Programming: From Problem Analysis to Program Design2 Objectives Learn more about the Framework Class Library Invoke methods in the String class Display message boxes Format numeric output Work with dates Read and write sequential files
Visual Basic.NET Programming: From Problem Analysis to Program Design3 Introducing the Framework Class Library Assembly –File with.dll suffix –Contains Intermediate Language (IL) Framework Class Library –Consists of approximately 100 assemblies Each containing one or more classes –Organized logically into namespaces
Visual Basic.NET Programming: From Problem Analysis to Program Design4 Introducing the Framework Class Library (continued) Namespace –Can contain both classes and other namespaces –System is root of all other namespaces Framework compilers do not automatically search all namespaces for classes used by code –Except System namespace –For all other namespaces Use Imports keyword
Visual Basic.NET Programming: From Problem Analysis to Program Design5
6 Invoking Methods in the String Class String data –Collection of characters String class –Member of System namespace. –Stored in reference variable Property –Special kind of VB.NET method –Access like public variable
Visual Basic.NET Programming: From Problem Analysis to Program Design7
8
9 Invoking Methods in the String Class (continued) String instances in VB.NET are immutable –Cannot be changed –Methods create and return new String Each character in String instance has index –Indicates position –Index for first character is 0
Visual Basic.NET Programming: From Problem Analysis to Program Design10
Visual Basic.NET Programming: From Problem Analysis to Program Design11 Using the Length Property Length property –Contains number of characters in String To access length for String s1: –s1.length
Visual Basic.NET Programming: From Problem Analysis to Program Design12 Using the Copy Method Creates copy of String instance Returns reference to new instance Example: –s2 = String.Copy(s1) Class method –Invoke using class name
Visual Basic.NET Programming: From Problem Analysis to Program Design13 Using the Chars Method Returns character located at specified index Example: –s1.Chars(6) Instance method –Invoke using reference variable name
Visual Basic.NET Programming: From Problem Analysis to Program Design14 Using the Equals Method See if two String instances contain same data Example: –s1.Equals(s2) Not same as =
Visual Basic.NET Programming: From Problem Analysis to Program Design15 Using the Substring Method Extract one or more characters from a String Return new String containing extracted characters Arguments: –Index of first character –Number of characters Example: –s2 = s1.Substring(0, 5)
Visual Basic.NET Programming: From Problem Analysis to Program Design16 Using the Replace Method Replace one or more characters in String –With one or more other characters Arguments: –String containing character(s) to be replaced –String containing replacement character(s) Example: –s2 = s1.Replace(“Hello”, “Hi”)
Visual Basic.NET Programming: From Problem Analysis to Program Design17 Using the Insert Method Add one or more characters into existing String –Beginning at specified index Example: –s2 = s1.Insert(6, “There “) Arguments: –Index where to begin insertion –Characters to be inserted
Visual Basic.NET Programming: From Problem Analysis to Program Design18 Using the StartsWith and EndsWith Methods StartsWith –Compares String with beginning character(s) of another String –Returns True or False Depending on whether there is a match EndsWith –Compares ending characters Use both methods to search for text containing specified characters
Visual Basic.NET Programming: From Problem Analysis to Program Design19 Using the StartsWith and EndsWith Methods (continued) StartsWith example: –s1.StartsWith(“Hi”) EndsWith example: –s1.EndsWith(s3)
Visual Basic.NET Programming: From Problem Analysis to Program Design20 Using the ToUpper, ToLower, IndexOf, and ToString Methods Change case of String value to uppercase or lowercase –ToUpper Uppercase –ToLower Lowercase
Visual Basic.NET Programming: From Problem Analysis to Program Design21 Using the ToUpper, ToLower, IndexOf, and ToString Methods (continued) IndexOf method –Search String instance for specific value –Returns index of first character of value –Or -1 If no matching value is found ToString –Convert numeric value to String
Visual Basic.NET Programming: From Problem Analysis to Program Design22 Displaying Message Boxes Use message box to –Display message –Get response MessageBox class –Member of System.Windows.Forms namespace –Single method named Show Creates instance of MessageBox Makes it visible
Visual Basic.NET Programming: From Problem Analysis to Program Design23 Displaying Message Boxes (continued) Show() method arguments –Message to display Can string literal or variable –Caption to display –Buttons to display –Type of icon to show
Visual Basic.NET Programming: From Problem Analysis to Program Design24 Example 6-12: Displaying message boxes 1. ' display a message 2. MessageBox.Show(“Hello Again”) 3. 'display a message and a caption 4. MessageBox.Show(“Hello Again”, “MessageBox Demo”) 5. 'display message, caption, Yes/No/Cancel buttons 6. MessageBox.Show(“Hello Again”, “MessageBox Demo”, MessageBoxButtons.YesNoCancel)
Visual Basic.NET Programming: From Problem Analysis to Program Design25 Example 6-12: Displaying message boxes (continued) 7. 'display message, caption, Yes/No/Cancel buttons, and Icon 8. MessageBox.Show(“Hello Again”, “MessageBox Demo”, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information)
Visual Basic.NET Programming: From Problem Analysis to Program Design26
Visual Basic.NET Programming: From Problem Analysis to Program Design27 Displaying Message Boxes (continued) Button combinations –Automatically displayed by IntelliSense After you type class name MessageBoxButtons –Select specific buttons to be displayed from list Icons –Displayed by IntelliSense when typing MessageBoxIcon
Visual Basic.NET Programming: From Problem Analysis to Program Design28
Visual Basic.NET Programming: From Problem Analysis to Program Design29
Visual Basic.NET Programming: From Problem Analysis to Program Design30 Displaying Message Boxes (continued) show() method return value –Data type DialogResult –Compare to specific values using If statement
Visual Basic.NET Programming: From Problem Analysis to Program Design31
Visual Basic.NET Programming: From Problem Analysis to Program Design32 Formatting Numeric Output Format numeric output to make it: –More attractive –Easier to read Use ToString method to format numeric data –Argument types: Format codes Format mask
Visual Basic.NET Programming: From Problem Analysis to Program Design33
Visual Basic.NET Programming: From Problem Analysis to Program Design34 Formatting Numeric Output (continued) Format mask examples: –s = phoneNo.ToString(“(###) ###-####”) –s = d.ToString(“$#,##0.00”) –ssNo.ToString(“###-##-####”)
Visual Basic.NET Programming: From Problem Analysis to Program Design35 Working With Dates FCL structures: –DateTime Contains actual date value –TimeSpan Contains computed difference between two dates –Belong to System namespace
Visual Basic.NET Programming: From Problem Analysis to Program Design36 Working With Dates (continued) Today –Property of DateTime –Gets system date –Returns DateTime instance. –Example: todaysDate = DateTime.Today Now property –Captures current time
Visual Basic.NET Programming: From Problem Analysis to Program Design37 Working With Dates (continued) Format date display –Invoke ToString method –Pass arguments that describe desired format Creating DateTime instance example: –eleanorsBirthday = New DateTime(1998, 12, 15)
Visual Basic.NET Programming: From Problem Analysis to Program Design38
Visual Basic.NET Programming: From Problem Analysis to Program Design39 Comparing Dates Subtract() method –DateTime class –Compute number of days between DateTimes –Returns instance of TimeSpan class TotalDays() method –TimeSpan class –Obtain number of days in TimeSpan
Visual Basic.NET Programming: From Problem Analysis to Program Design40 Example 6-18: Computing the Difference between Dates 1. ' compute the difference between two dates 2. Dim daysDifference As Double, ageDifference As TimeSpan 3. ageDifference = emilysBirthday.Subtract(eleanorsBirthday) 4. daysDifference = ageDifference.TotalDays() 5. Console.WriteLine(“The age difference is “ & daysDifference)
Visual Basic.NET Programming: From Problem Analysis to Program Design41 Comparing Dates (continued) Compare() method –DateTime class –Compares two DateTime instances –Returns either: 0 +1
Visual Basic.NET Programming: From Problem Analysis to Program Design42 Performing Arithmetic with Dates DateTime class –Methods add a value to month, day, or year –Named AddMonths, AddDays, AddYears, etc. –Example: todaysDate.AddMonths(1)
Visual Basic.NET Programming: From Problem Analysis to Program Design43 Reading and Writing Sequential Files Classes typically employed in sequential file processing: –StreamWriter –StreamReader Database –Data organized into one or more tables –Tables can be related
Visual Basic.NET Programming: From Problem Analysis to Program Design44 Reading and Writing Sequential Files (continued) Files –Contain data –Organized into fields and records Field –Individual data item –Can be contained in a primitive variable or String instance Record –Consists of one or more related fields
Visual Basic.NET Programming: From Problem Analysis to Program Design45 Reading and Writing Sequential Files (continued) File –Contains one or more related records Sequential file –Data organized with one data item following another –System.IO namespace classes: StreamWriter StreamReader. Must use Imports statement
Visual Basic.NET Programming: From Problem Analysis to Program Design46 Reading and Writing Sequential Files (continued) StreamWriter class –WriteLine() method –Can overwrite or append file StreamReader class –ReadLine() method –Write loop when reading from sequential file –Check for existence of data before reading data –Use Peek() method
Visual Basic.NET Programming: From Problem Analysis to Program Design47 Example 6-22: Appending to a Sequential File 1. Dim customerFile As New StreamWriter("C:\Customers.txt", True) 2. customerFile.WriteLine("Graham") 3. customerFile.WriteLine("Marietta") 4. customerFile.WriteLine(" ") 5. customerFile.Close()
Visual Basic.NET Programming: From Problem Analysis to Program Design48 Programming Example: Employee Report Input –Sequential file named C:\Employee.txt containing employee information Output –Employee report containing: 1. Social Security number formatted nnn-nn-nnnn 2. Date employed formatted as monthname dd, yyyy 3. Hourly pay rate formatted as currency 4. Formatted employee name
Visual Basic.NET Programming: From Problem Analysis to Program Design49 Summary Visual Basic.NET stores string data in instances of String class –Provides several useful methods and properties –Immutable MessageBox –Used to display message and get response Invoke ToString method in primitive structures to format numeric data
Visual Basic.NET Programming: From Problem Analysis to Program Design50 Summary (continued) Work with dates using: –DateTime –TimeSpan VB.NET uses two classes in System.IO namespace to work with sequential files: –StreamWriter –StreamReader