Home
Unit 14: Event-Driven Programming
Contents
1. jes i da 44 2 9 e u gt 2a Object as shown in the image on the aes erormanceLounter ERE Forts Deion x left Do not make the mistake of adding E Phices ooo lots of Timers in the hope of getting Asien Directory one to attach itself to the form L Time EventLog FileSystemWatcher In order to gain access to the default event of the Timer object double click on the Timer itself The default event HelpProvider ImageList MessageQueue i7 eainiie o Andas Feia Cini of the Timer object is the Tick event but the default a timing between the Ticks is not set to 1 second the default timing is 1 10 of a second or an Interval of 100 An Interval of 1000 is equal to 1 second in real time You NaanCatiinNianlaan can change the Interval in the Properties Window of the Timer control There are many more Events that can be used with the Timer control and can be accessed via the pull down list of events shown in the red highlight below o0 WindowsApplication1 Microsoft Visual Studio File Edit View Project Build Debug Team Data Tools Test Window Help ae ca dg aalala a w a SCP Debug JQ Fig Be MS E WindowsApplication1 There are no usable controls in this group Drag an item onto this text to add it to the toolbox Sa My Project Private Sub Timer1_Tick ByVal sender As System Object ByVal e As System EventArgs Handles Timer1 Tick E Form1 vb End Sub End Class The way t
2. ProgressB ar RadioButton RichT extBox If you wish to TextBox resize the form ee l roperties Avai lable grab any of the Form System Windows Forms Form AOE a Solution Explorer game E i a controls i handles shown M0 shown here here and pull i MainMenuStrip MaximizeBox MaximumSize MinimizeB ox MinimumSize Properties of the current O SplitContainer TabControl a TableLayoutPanel D ii m oO Q a amp Toolbars RightT oLeft fo rm shown hm Pointer RightT oLeftLayout E ContextMenuS tri Showlcon h ere E i P ShowlnT askbar C MenuStrip Softwa re Size 300 300 k StatusStrip A SizeGripStyle Auto z ToolSti st at u S 1 S StartPosition WindowsD efaultLocation me P Ei ToolStripContainer sh own h ere Text Form1 Pers Tanhdoast F alza a Pointer xt The text associated with the control o 9 Jane Fletcher South Nottingham College lh Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Form control Lecturer Jane Fletcher Commonly used properties for the Form control Name The Name property is what you want to call the form within the program It is usually left as its default which is Form1 Form2 and so on If you wi
3. Exit Sub End If If Not IsNumeric txtSecondNumber Text Then MsgBox You have entered a non numeric value MsgBoxStyle Critical Error txtSecondNumber Text txtSecondNumber Focus Exit Sub End If intSecondNumber txtSecondNumber Text If intSecondNumber lt 1 Or intSecondNumber gt 1000 Then MsgBox You have entered a number out of range MsgBoxStyle Critical ERROR txtSecondNumber Text txtSecondNumber Focus Exit Sub End If Alter the height of the form Me Height 364 End Sub Private Sub radAdd CheckedChanged ByVal sender As System Object ByVal e As System EventArgs _ Handles radAdd CheckedChanged The user wants to add up the two numbers decTotal intFirstNumber intSecondNumber lblAnswer Text intFirstNumber amp amp intSecondNumber amp amp decTotal Increase the size of the form Me Height 546 End Sub Private Sub btnClear_Click ByVal sender As System Object ByVal e As System EventArgs Handles _ btnClear Click Shrink the form and clear the text boxes Me Height 191 txtFirstNumber Text txtSecondNumber Text txtFirstNumber Focus End Sub Private Sub radSubtract_CheckedChanged ByVal sender As System Object ByVal e As _ System EventArgs Handles radSubtract CheckedChanged The user wants to subtract the two numbers decTotal intFirstNumber intSecondNumber lblAnswer Text intFirstNumber amp amp intSecondNu
4. Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 2 Using Labels Buttons and TextBoxes Lecturer Jane Fletcher Exercise 2 1 Enter your name Surname Fletcher Jane Fletcher welcome to GroupBox2 i lbIMessage programming alll Display message MESSage A program is needed to meet the following requirements Upon first load all objects on the form should be visible and the cursor should be flashing in txtName When the user clicks btnDisplay the name entered into txtForename and txtSurname should be displayed along with the message welcome to programming in lblMessage When the user clicks btnRemove lblMessage should blanked out the text in txtForename and txtSurname should be removed and the cursor should be put into txtForename The cursor should tab between Forename and Surname accurately When the user clicks btnClose the program should close D Jane Fletcher South Nottingham College pama a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Lecturer Jane Fletcher 3 0 Specification for program developed in class Ee Mini Calculator x Enter 2 numbers First 5 Se
5. BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Data types Lecturer Jane Fletcher Visual Basic Common language Nominal storage Value range type runtime type allocation structure Single single i 3 4028235E 38 through 1 401298E 45 for negative precision values floating point 1 401298E 45 through 3 4028235E 38 for positive values String variable String class Depends on 0 to approximately 2 billion Unicode characters length implementing platform UlInt32 O through 4 294 967 295 unsigned ULong Ulnt64 8 bytes 0 through 18 446 744 073 709 551 615 1 8 E 19 unsigned User Defined inherits from Depends on Each member of the structure has a range determined structure vata implementing by its data type and independent of the ranges of the platform other members Ulnt16 2 bytes O through 65 535 unsigned t In scientific notation E refers to a power of 10 So 3 56E 2 signifies 3 56 x 10 or 356 and 3 56E 2 Reference taken from http msdn microsoft com en us library 47zceaw v vs 80 aspx ae Jane Fletcher South Nottingham College j Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Arithmetic and logical operators Lecturer Jane Fletcher Arithmetic and logical comparisons can be performed within any comput
6. Remove the label from the screen by altering the Visible property lblMessage Visible False End Sub End Class Gee 3 Jane Fletcher South Nottingham College 2_ _ SL SG 50 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 1 Using Labels and Buttons Lecturer Jane Fletcher Exercise 1 1 i First program playing with buttons i Welcome to Programming lbIMessage Click one and see what happens btnDisplay m E m Display message a btnRed btnBlack btnWhite btnGreen Remove message Close btnClose A program is needed to meet the following requirements Upon first load lblMessage should not be visible When the user clicks btnDisplay lblMessage should be displayed When the user clicks btnRemove lblMessage should be taken off the screen When the user clicks btnRed the background of lblMessage should become red and the text colour should be white This requires you to access the ForeColor and BackColor properties of the label on the click event of btnRed When the user clicks btnBlack the background of lblMessage should become black and the text colour should be white This requires you to access the ForeColor and BackColor properties of the label on the click event of btnBlack When the user clicks btnWhite the background of lblMessage should
7. You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwooO Now enter 10000 into the box alongside the prompt First Number and click the Process button Input in first number is too long X You must enter a number in the range of 1 to 9999 You will be shown an error message Look at the top line of this error message it says Input in first number is too long in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwoo 103 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives User documentation Lecturer Jane Fletcher To finish off Lesson 1 enter 75 into the box alongside First Number and click on the Process button Lesson 2 Entering information into Second Number Nothing entered into Second Number at all Load TwoPlusTwoO and at the prompt Second Number don t enter anything before you click the Process button TwoPlusTwo will generate an error message No input in Second number X You must enter a number in the range of 1 to 9999 Loo
8. name you are now ready to print should be displayed in lblStatus where name is the value stored in strName 9 The Preview menu strip click event should contain the following code KR WN Start the print preview dialog box off in maximised state PrintPreviewDialog1 WindowState FormWindowState Maximized PrintPreviewDialog1 Document PrintDocument1 assign a document to Print Preview control PrintPreviewDialog1 ShowDialog display the PrintPreview dialog box 10 The PrintDocument1_PrintPage event gained by double clicking on the PrintDocument object added to the form should contain the following code and comments Dim MyTitleFont As New Font Courier New 14 FontStyle Underline Dim MyHeaderFont As New Font Courier New 12 FontStyle Italic Dim MyFont As New Font Courier New 12 FontStyle Regular Dim MyFormat As String 25 1 15 2 15 3 15 4 columns Dim intTitleX intX intY intFontHeight As Integer intTitlexX 175 intX 100 set coordinates for first thing to print intY 5 intFontHeight MyFont GetHeight e Graphics height of 1 line of font used normal font not title font e Graphics DrawString P OE TRY CORNER _ MyTitleFont Brushes Black intTitlexX intY Put the title on the page intX 50 This is how far you want to indent from the edge of the page ee ee 0 Jane Fletcher South Nottingham College ymae N i EEN Unit 14 Event Driv
9. Login option is highlighted Below it there is a line of text saying Click here to log in This is another easy way to give your project a more professional appearance the Tooltip Using the Tooltip control See pages 43 and 44 for an explanation of using the ToolTip object As explained there it is an excellent way of providing onscreen help for the user and for partial meeting of the criterion P6 for Unit 14 Event Driven Programming Try hovering over the Ribbon in Microsoft Word if you want to see some very well designed usage of the ToolTip object The key thing is to always be professional in your messages to the user swearing joking etc may appear to be a good idea and the height of sophisticated wit when you are in the classroom but neither make users or lecturers smile D Jane Fletcher South Nottingham College y aaee 646 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Design documentation Lecturer Jane Fletcher Part of the project development process is the creation of the design documentation that goes with each project that is created For each of the programs that you will create in class you will be given partial documentation you will be given a program specification a detailed breakdown as to how the project should function including any validation and processing requirements b
10. Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips i a S Lecturer Jane Fletcher 24 All group boxes must be disabled at this point so that the only option open to the user is to select the File menu Behind the scenes 25 For each of the number buttons the coding is the same so the one click event is to be used for all of them Use the sender text method of ascertaining which number has been clicked and store the sender text in intFirst n 147 Jane Fletcher South Nottingham College p UN Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips Lecturer Jane Fletcher Coding for the program Public Class Form1 Dim Dim Dim Dim bFirst As Boolean intFirst intSecond As Integer decAnswer As Decimal strOperator As String Private Sub CloseToolStripMenuItem Click ByVal sender As System Object _ End ByVal e As System EventArgs Handles CloseToolStripMenuItem Click Close the project End Sub Private Sub Form1_Load ByVal sender As System Object ByVal e As System EventArgs _ End Handles MyBase Load Alter the colour of the menu strip MenuStrip1 BackColor Color White Set the height o
11. amp intNumberOfDecimalPlaces amp _ decimal places Your value is amp _ FormatNumber decNumber intNumberOfDecimalPlaces FormatNumber the first number is what you want to display and the second is to how many decimal places However it doesn t move the decimal place within the digits of the first number for that you have to do a little bit more work as below Dim decAnswer As Decimal Select Case intNumberOfDecimalPlaces Case decAnswer decNumber Case 1 decAnswer decNumber 10 Case 2 decAnswer decNumber 100 Case 3 decAnswer decNumber 1000 Case 4 decAnswer decNumber 10000 End Select lstOutput Items Add Or did you mean like this amp decAnswer txtDecimalPlaces Text txtDecimalPlaces Focus End Sub End Class ee Yh eee 3 Jane Fletcher South Nottingham College pae Unit 14 Event Driven Programming SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Example programs 9 Formatting numbers Exercise 9 1 Using the Format statement Enter your number Using named numeric formats General Humber Fixed Standard Percent Currency Using user defined numeric formats g 0 00 HHH OO HHO O0 HH O EH HO OO 0 0 Clear advancing learning changing lives Lecturer Jane Fletcher 123456 7590 1234567890 1234567890 00 1 234 567 890 00 1234567890
12. 2 Menustrpt File 3____ CloseToolStripmenultem Close 4 Groupboxt 5 fae Label2 Button3 btnClear 8 TextBox surname a el eeses s _OSOsOssssseesSesSeSee 206 Jane Fletcher South Nottingham College __ 64 66a 4 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to refresh your memory on using listboxes 1 Throughout the program use the font of your choice 2 When the form loads ensure that the background colour of the menustrip is the same as the background colour of the form Place focus in the Forename text box 3 Declare these variables at the top of the program Dim MyFormat As String 10 1 15 2 5 Dim strForename As String Dim strSurname As String Dim strGroup As String 4 The Close button should close the program 5 Coding for btnProcess a btnProcess should validate user input the input for each item should exist and if not this should result in a message box to the user and the cursor replaced into the correct text box to await further user entry If input exists then it should be moved to either strForename or strSurname and converted to proper case i e a capital letter fo
13. 9 The New User button should initialise strPassword to a null value set lblPassCode s text to blank and reset the form to its original size 10 Once the user has clicked on one of the numbered buttons to indicate which user they are the screen should be enlarged to display the second group box strPassword should be set to equal null value and intUser should be assigned the value of the sender s text NOTE the User buttons will all work under the same subroutine the programmer should add each button s click event to the procedure for btnUser1_Click as shown below ef ees _a e esNeN V VLV LCAUCONnn9n 199 Jane Fletcher South Nottingham College yee O Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 12 Creating a Login system Lecturer Jane Fletcher Private Sub btnUser1 Click ByVal sender As System Object _ ByVal e As System EventArgs _ Handles btnUser1 Click btnUser2 Click _ btnUser3 Click btnUser4 Click btnUser5 Click _ btnUser6 Click 11 The buttons btnPass1 btnPass6 will work in a similar fashion as in step 6 For each click of a button the variable strPassword should be concatenated with the sender s text strPassword strPassword amp sender text and the value currently in strPassword should be displayed in lblPassCode 12 When the user clic
14. Color White The following code is to work out what day it is today intDay Date Today DayOfWeek Generates an integer value 1 for Monday 2 for Tuesday and so on Select Case intDay Case 1 strDay Monday Case 2 strDay Tuesday Case 3 strDay Wednesday Case 4 strDay Thursday Case 5 strDay Friday Case 6 strDay Saturday Case 7 strDay Sunday End Select Display the complete date in the label lblTodaysDate Text strDay amp amp Date Today End Sub Private Sub dtpSelectedDate CloseUp ByVal sender As Object ByVal e As System EventArgs _ Handles dtpSelectedDate CloseUp The default event for a date time picker is the ValueChanged event The CloseUp event means that the user has used the DTP and has now moved on from it ee ee 63 Jane Fletcher South Nottingham College je __a__aS aa aun _ Ma lt lt nM6 ea Unit 14 Event Driven Programming edexce l SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher Assign the value of the date time picker to the date variable dtSelectedDate dtSelectedDate dtpSelectedDate Value Date Work out the difference between the date the user has picked and Christmas day using days as the outcome not months or years Dim intDaysDifference As Integer intDaysDiffere
15. End If End Sub Private Sub chkWednesday_ CheckedChanged ByVal sender As System Object _ ByVal e As System EventArgs Handles chkWednesday CheckedChanged Enter the name and day worked into the list box If chkWednesday Checked True Then lstHistory Items Add txtForename Text amp amp txtSurname Text amp works on Wednesday SetListBox End If End Sub Private Sub chkThursday_CheckedChanged ByVal sender As System Object _ ByVal e As System EventArgs Handles chkThursday CheckedChanged Enter the name and day worked into the list box If chkThursday Checked True Then lstHistory Items Add txtForename Text amp amp txtSurname Text amp works on Thursday SetListBox End If End Sub Private Sub chkFriday_CheckedChanged ByVal sender As System Object _ ByVal e As System EventArgs Handles chkFriday CheckedChanged Enter the name and day worked into the list box If chkFriday Checked True Then lstHistory Items Add txtForename Text amp amp txtSurname Text amp works on Friday SetListBox End If End Sub Private Sub btnDeleteSelected Click ByVal sender As System Object _ ByVal e As System EventArgs Handles btnDeleteSelected Click Remove the line from the list box that the user has selected If lstHistory SelectedIndex 1 Then the user hasn t selected anything MsgBox You must select a line to delete before pressing this button _ MsgBoxStyle Critical ERROR Exit Sub End
16. It represents a branch in program logic where a decision is required as to the next course of action based on condition s stipulated by the programmer at design time There are several different types of selection constructs ranging from the simple If Then Statement to the complex Select Case statement If Then End If This is the most basic of the Selection construct The format of the statement is If Comparator1 LogicalOperator Comparator 2 Then Actions statements End lf where Comparator and Comparator2 could be the values contained within an object a text box in the example below or a variable and LogicalOperator is the method the comparison is to take such as equal to greater than less than etc see pages 66 68 Then is the keyword that pairs with the If statement and End If is the key phrase that ends any lf statement regardless of the format of that If statement as long as the If occurs on more than one line The Visual Basic editor will automatically indent any action statements that occur between the If Then and End If which aids readability In this context action statements are lines of VB NET code that perform whatever is required should the condition stated in the If statement be met This procedure determines the highest number from a pair entered by the user Examine the contents of the two text boxes by looking at the text property of each If txt
17. SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips lt lt lt lt lt lt _ Lecturer Jane Fletcher Processing Numbers Processing Numbers File Help File Help The purpose of this program is to enter two numbers each of wific About shown must be within the range of 1 to 100 then to select an operator to use on these numbers Once you ve clicked on an operator the answer will be displayed Step 1 Enter number to process E After Return key 2 pressed on About screen Step 2 Select Operator Step 3 Display Answer 10 2 20 00 Go to File and New to continue Instead of from a specification write the project above from the structured English given Structured English for this program Form_Load Set the height of Form1 to be 182 Set focus to txtNumber End of Form_Load btnProcess_Click If the length of the entry in txtNumber1 0 Then Display a message box saying You must enter a number in the first box Set the cursor focus to txtNumber 1 Quit the subroutine End If If the length of the entry in txtNumber1 is gt 3 Then Display a messagebox saying You must enter a number in the range of 1 to 100 in the first box Blank out the text in txtNumber Set the cursor focus to txtNumber 1 Quit the subroutine End If If the entry in txtNumber1 is
18. Windows Form sale f Font Format Long GenerateMember True ImeMode NoContral Location 35 33 Locked False Margin 3 3 3 3 MaxDate 31 12 9998 Maximumsize 0 0 MinDate 01 01 1753 Microsoft Sans Serif MinDate The minimum date that can be selected lt is important to remember when using a DateTimePicker that the Value property contains both a date aspect as well as a time aspect the key is in the control s name really but because when at run time the control displays only a date choice the time aspect is often overlooked If you re trying to work out the difference between two dates for example the time factor stored in a date variable taken from the Value property of a DateTimePicker will have an associated time and so if the first date to be used in the equation is in the afternoon and the second date in the morning then you won t get a complete day s difference so the answer you have may be unexpected The answer you get isn t in rounded up full days so a difference of 23 hours and 59 minutes is 0 days U i lt i lt i i C 32 Jane Fletcher South Nottingham College a mnm Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls DateTimePicker control Z Lecturer Jane Fletcher The default event for the DateTimePicker control is the ValueC
19. oa ReturnToolStripMenultem Return Label1 Fes 93 Jane Fletcher South Nottingham College lt _ lt 66664 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 12 Creating a Login system Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to create the very simplest login screen 1 When the program loads only the top part the form should be visible 2 Throughout the program use the font of your choice 3 Declare two variables at the top of the program Dim intUser As Integer Dim strPassword As String 4 The Close button should close the program 5 The New User button should initialise strPassword to a null value set blPassCode s text to blank and reset the form to its original size 6 Once the user has clicked on one of the numbered buttons to indicate which user they are the screen should be enlarged to display the second group box strPassword should be set to equal null value and intUser should be assigned the value of the sender s text NOTE the User buttons will all work under the same subroutine the programmer should add each button s click event to the procedure for btnUser1_Click as shown below Private Sub btnUser1 Click ByVal sender As System Object _ ByVal e As System EventArgs
20. tbChoice4 5 ea Yee 6 Jane Fletcher South Nottingham College paee 45 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to illustrate how to make the TabControl object work when the tabs themselves are clicked The next program Exercise 10 1 will show how to use them without having to click them 1 When the program loads the entire form should be visible 2 Throughout the program use the font of your choice 3 The Close button should close the program 4 The TabControl should be renamed to tbMenu 5 In the TabPages property of tbMenu five tabs should be declared and named as follows First page tblintro Second tbChoice1 Third tbChoice2 Fourth toChoice3 Fifth tbChoice4 PAA TD 6 The TabControl should then be drawn using the following code in the Drawltem process of that object This subroutine is called every time the tabs are accessed Firstly we ll define some parameters These are used to draw the tabs Tabs aren t objects like we know them they are drawn fresh each time we use them Dim CurrentTab As TabPage tbMenu TabPages e Index Dim ItemRect As Rectangle tbMenu Ge
21. the answer isn t started programming in the first place 8 How do I make a different style of typeface appear on every object on a form 9 Name four properties that will change the appearance of a label 10 How do stop the graphical user interface from appearing anywhere it likes on the computer screen when run the program 11 How do start to internally document a program ea a err TTTTL T LCUOCOtitiwi nw 45 Jane Fletcher South Nottingham College p lt Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Revision questions Exercise 2 Lecturer Jane Fletcher 1 What property do you change on a button to stop the user being able to click on it but with it still being visible 2 What object could a programmer use to cluster together a group of related objects 3 When is it allowable not to rename an object from its default name 4 Where would you find the executable version of your program if you were using Windows explorer 5 Name three events that you can use with a Button object 6 My text box won t allow me to stretch it downwards to enter more text What property do have to change 7 What two ways can use to make sure that the cursor is in the text box want it to be in when the program starts running 8 Give r
22. the first thing you need to consider is whether the data is numeric or non numeric If the data is numeric then you have further decisions to make because you have to work out what type of numeric data it is For example is the data integer whole number decimal a small number with decimal places a really large number with lots of decimal places and so on You also have to take into account what precision is required if you are calculating Pi to 1 000 decimal places then this will require more precision than if you are adding up the cost of three CDs that you re buying in a shop When you are writing your validation code these are the things you must consider Whether there is anything entered in the first place Whether the thing that is entered is too long Whether the thing that is entered is of the correct type this applies to numeric data Whether the thing that is entered is within the correct range this applies to numeric data There are more things to consider when validating user input but the above items are the most important The coding below is written to ensure that the user has entered a numeric value in the range of 99p to 99 99 into the TextBox object txtlnput and belongs to the Click event of btnValidate Private Sub btnValidate Click ByVal sender As System Object _ ByVal e As System EventArgs Handles btnValidate Click Check that the user has actually entered something and display a message to the
23. 1411664470 Troelsen A Pro C 2005 and the NET 2 0 Platform 3rd Edition Apress US 2004 ISBN 10 1590594193 ISBN 13 978 1590594193 Websites eventdrivenpgm sourceforge NET www vbexplorer com VBExplorer VBExplorer aspte www vbwm com R 233 Jane Fletcher South Nottingham College fg lt lt S SS _ v _ lt lt Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 2 Glossary of Terms Lecturer Jane Fletcher This unit relies on your understanding of some fairly complex programming terminology As the unit progresses and your learning increases you should keep this glossary up to date to that you can refer to it when you need to Term Definition LO 1 Understand the features of event driven programming Service oriented Time driven Event handlers Trigger functions Events Examples of events Mouse Keyboard HTML object Form User interface Event loops Flexibilit Suitability for GUI Simplicity for programming Ease of development LO 2 Be able to use the tools and techniques of an event driven language Triggers Examples of triggers Key press Alarm System event Touch screen event Mouse Click N W Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Exten
24. 8 1 165 8 2 Using DateTimePickers Exercise 8 2 167 9 Formatting numbers 9 0 Formatting numbers Done in class 170 9 1 Formatting numbers Exercise 9 1 174 10 Using TabControls 10 0 Using TabControls Done in class 176 10 1 Using TabControls Exercise 10 1 181 11 Using WebBrowsers 11 0 Using WebBrowsers Done in class 184 11 1 Using WebBrowsers Exercise 11 1 189 12 Creating a Login System 12 0 Creating a login system Done in class 193 12 1 Creating a login system Exercise 12 1 198 13 Recapping with ListBoxes 13 0 Recapping with ListBoxes Done in class 201 13 1 Recapping with ListBoxes Exercise 13 1 206 U Y Jane Fletcher South Nottingham College J E LLMM Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development EG Lecturer Jane Fletcher Topic Page 14 Printing 14 0 Printing Done in class 209 14 1 Printing Exercise 14 1 215 15 Updating information in a ListBox 15 0 Updating information in a ListBox Done in class 21 15 1 Updating information in a ListBox Exercise 15 1 224 16 Printing from a ListBox 16 0 Printing from a ListBox Done in class Exercise on last page 228 Appendix 1 Unit Specification 230 Appendix 2 Glossary of Terms 234 Appendix 3 Log of Completed Exercises 237 Index 239 Jane Fletcher South Nottingham College Unit 14 Event Driven Program
25. An example of the difference between data and information is when a user collects answers to a set of questions in a questionnaire and organises them to put into a computer program That is data When the user has entered this data into the program and processed it it becomes information Data Part of the programming editor software that allows the programmer to use various tools to ensure the eventual correct processing of the program Debuggers allow the programmer to halt execution of the program and to examine the contents of variables fields The part of the program life cycle that comes before coding putting objects controls onto a form to meet the designs contained within the program specification l The section of the program editor that allows the programmer to put controls objects E EEN onto a form A window that appears usually within the Design view of the Editor requesting further Debugger Design input from the user Examples include Font dialog box and the Items Collection Editor of a MenuStrip control Dialog box Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Quick start to terminology used in this unit f Lecturer Jane Fletcher Disabled A control that is disabled is one that has been deactivated by the programmer and cannot
26. Checked False chkFriday Checked False txtForename Focus End Sub Private Sub SetListBox Dim intTempCount As Integer lstHistory Items Count lstHistory SelectedIndex intTempCount 1 End Sub End Class 4 138 Jane Fletcher South Nottingham College pae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes lt lt lt lt lt lt _ Lecturer Jane Fletcher Exercise 5 1 First check boxes Enter name 2 Forename Jane 5 Es Surname Fletcher 6 Pick days worked 8 9 10 11 12 and 13 wW Monday wW Tuesday wW Wednesday Thursday w Friday Employment history Jane Fletcher works on Monday i Delete Selected Jane Fletcher works on Tuesday Jane Fletcher works on Wednesday Delete All This person works 5 days Jane Fletcher works on Thursday 4 Enter another 9 employee 0 Jane Fletcher works on Friday a Z vw 3 tem tem 1 GroupBox1 2 CheckBox4 chkThursday Label1 CheckBox5 chkFriday abel2 4 TextBox txtForename extBox2 txtSurname utton1 btnProcess GroupBox3 ListBox1 lstHistory Button2 btnDeleteSelected Button3 btnDeleteAll oe oe eS oM a CO NI OY O1 WW gJ GroupBox2 gbDays Label3 lblCount CheckBox1 chkMonday 19 Button4 btnEnterAnotherEmpl
27. Display Message move to the Properties Window Scroll to the Text property and delete Button1 Type in Display Message Click back onto the Form object and notice that the text of the button has changed The default event of the Button object is the Click event In order to get to the Source Code window for the button we ve just created double click anywhere on the button object on your form The Click event for that button will be created and you will be in the Source Code Window You will see something like the image below and your cursor will be flashing between the lines containing Private Sub btnClick_Click and End Sub WindowsApplication1 Microsoft Yisual Studio File Edit View Project Build Debug Team Data Tools Architecture Test Analyze Window Help DeGe aa s5BRlalS2 9 C A Glo u aed JAFRA AE an1 YD L Eesign Solution Explorer o binClick i YG Click n 3 Aele su O O OUO U a Winonsaooieation There are no usable controls in this group Drag an item onto this text to iene Sa My Project add it to the toolbox Forml vb A Private Sub btnClick_Click ByVal sender As System Object ByVal e As System EventArgs Hand End Sub End Class The Click event is as stated above the default event for the Button object However there are many other events that it is possible to access To get to those make sure that the button object s name appears in the Object
28. Each Next statement counts 2 12 2 how many sums have been performed and displays this information in the last line of the list box Lecturer Jane Fletcher There are 12 items in the list box Do While Loop and Do Loop While The Do While Loop and Do Loop While are very similar There is however a difference between the two Do Loop While will perform the action statements within it at least once whereas with Do While Loop if the condition set after the word While is met already the loop will not be performed at all With Do Loop While the action statements within the loop will be performed at least once Formats for these statements are Do While condition Action statements Loop and Do Action statements Loop While condition In the example below the user is asked to enter two numbers the first one is the number to add up and the second one is the total that we mustn t go over Notice in the first screenshot below the coding that when both numbers are equal the loop isn t actually performed The purpose of this block of code is to take the values from the two text boxes entered by the user and to add the first number to a total that starts from the first number and keep adding that number to the total until the total is greater than the second number entered Dim intTotal As Integer Used to accummulate all additions performed on the first number Dim intFirstNum
29. General ES There are no usable controls in of ear this group Drag an item onto 4 Visual Studio 2010 Professional this text to add it to the toolbox Get Started Guidance and Resources Latest News C aan APS Connect To Team Foundation Server ro New Project lt F Open Project To J What s New in Visual Studio 2010 Learn about the new features included in this release Welcome Windows Web Cloud Office SharePoint Data ell FKt es 62 Jane Fletcher South Nottingham College a mnm Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Loading an existing project Lecturer Jane Fletcher Find the Solution file belonging to the Pre project that you want to open and click on GO Exercise done in _prjWeekOneDonelnClass v 4 Search priWeekOneDonelnClass P it then click on the Open button Oami Peent teil Oh o Microsoft Visual St Documents library pee eS 2 i J Weekly Program prjWeekOneDonelnClass ae Alternatively you can double click on the aaa ar aa OEE Solution file and the project will open Kawo Il WB paastonsnonsncee 04 07 201211 50 File folder W TE CE prWeekOneDonelnclass gt 04 07 2012 11 50 Microsoft Visual Fom ve Design gt lt i Recent Places Libraries Documents a Music Pictu
30. If lstHistory Items RemoveAt lstHistory SelectedIndex MsgBox Line deleted MsgBoxStyle Information Successful deletion End Sub ee lt a a wddsC tCtC ee 37 Jane Fletcher South Nottingham College a mnm ON Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Private Sub btnDeleteAll Click ByVal sender As System Object _ Lecturer Jane Fletcher ByVal e As System EventArgs Handles btnDeleteAll Click Ask the user if they really mean to delete everything Dim intResponse As Integer intResponse MsgBox Do you really wish to delete everything _ MsgBoxStyle YesNo Are you sure If intResponse vbYes Then they do lstHistory Items Clear txtForename Text txtSurname Text txtForename Focus MsgBox Information cleared MsgBoxStyle Information _ All information deleted Else MsgBox No information deleted MsgBoxStyle Information _ No action taken End If End Sub Private Sub btnEnterAnotherEmployee Click ByVal sender As System Object _ ByVal e As System EventArgs Handles btnEnterAnotherEmployee Click Reset everything back to the beginning txtForename Text txtSurname Text gbDays Enabled False chkMonday Checked False chkTuesday Checked False chkWednesday Checked False chkThursday
31. If the user clicks radAdd then the program must add the two numbers together in the default CheckChanged event for the radio button and display the total in lblAnswer in the format shown here First number entered second number entered the answer Where first number entered is the value in intFirstNumber and so on The other radio buttons should work in a similar way but should perform the appropriate arithmetic operation and display btnClear when clicked should put the form back to its original size clear both text boxes and put the cursor into txtFirstNumber oa 9 Jane Fletcher South Nottingham College S S Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Coding for the program Lecturer Jane Fletcher Public Class Form1 Dim intFirstNumber intSecondNumber As Integer Dim decTotal As Decimal Private Sub Form1_Load ByVal sender As System Object ByVal e As System EventArgs _ Handles MyBase Load Shrink the size of the form Me Height 191 End Sub Private Sub btnContinue Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnContinue Click Move the values from the text boxes into the integer variables but only if they are valid Non valid input should be thrown out If txtFirstN
32. Lecturer Jane Fletcher You will be shown an error message Look at the top line of this error message it says Input in Second number isn t numeric in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusT woo You enter a number that is out of the accepted range of 1 to 9 999 Type 0 into the box alongside the prompt Second Number and click the Process button Input in Second number ts out of range Ea X You must enter a number in the range of 1 to 9999 You will be shown an error message Look at the top line of this error message it says Input in Second number out of range in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwooO Now enter 10000 into the box alongside the prompt Second Number and click the Process button Input in Second number is too long ee X You must enter a number in the range of 1 to 9999 You will be shown an error message Look at the top line of this error message it says Input in Second number is too long in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you
33. Resource dialog box opens as shown here to the right Click on the Local resource radio button then click the Import button From there the Open screen opens allowing you to navigate through your computer files to locate the f picture of your choice Once you have found your picture click Open In the illustration to the right notice that have selected to add the picture called Penguins to my PictureBox Click the OK button However the image is not fully included due to the fact that it is too large to fit within the size of PictureBox that we have to work with To allow the entire image to display without resizing the PictureBox click on either the small arrow to the top right edge of the PictureBox or go to the SizeMode property in the Properties Window both give you to the same options The default is Normal which keeps the PictureBox and image to their original size thus losing every part of my penguin except its right ear Stretchimage allows the entire image to be displayed however if the PictureBox is not the correct size then the image will be distorted and will need to be manually altered O KF t i s s sts SNNOsOsO_OOOOS 35 Jane Fletcher South Nottingham College anme N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma fo
34. The format of this statement is For Each Element in Group Action statements Next where Element is the thing in the Group that you want to process In the example below this coding will follow the coding from the For Next example above and will count how many iterations have been performed in the For Next process using the For Each statement based on the Items in lstAnswer This is a silly exercise to perform because we know that one of the inputs from the user is exactly that information but this is used here as a simple example of how to make a For Each Next statement work The output from the program is displayed below the coding Dim intSumCount As Integer Used to count up how many sums have been performed and put into the list box Using For Each add one to intSumCount to count how many items are in the list box For Each Item In lstAnswer Items Add one to intSumCount intSumCount 1 Next Display the counter at the bottom of the list box lstAnswer Items Add There are amp intSumCount amp items in the list box n Im IIM 74 Jane Fletcher South Nottingham College a mnm N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures J In the example screenshot here the user has entered that the number 12 j 43273 should be multiplied from 1 to 12 and For
35. applied when altering the form s background colour BorderStyle The default BorderStyle is None which means that the label will have no edges Other options are FixedSingle which would give the label a black line drawn around its edges or Fixed3D which makes the edges of the label appear in relief giving a reverse embossed effect If the software needs to draw attention to some information displayed within a label setting a different border style can draw the user s eye to it Enabled It isn t usual to enable a label since it doesn t normally have any coded event attached to it However if there is an event that will occur then setting the Enabled property to False in either the Properties Window at design time or during run time will cause the label to appear to be greyed out and will disable any event handler attached to it Setting the Enabled property to True will turn it back on again Font Determines the size style and type of font to be used in the Text property of the label Clicking on the ellipses to the right of the Font property in the Properties Window generates the Font Dialog Box which allows the developer to select his or her choice of font style size ForeColor The colour of the text within the label Unless you change this property the label will have the default foreground colour similar to the Form object Location Where the object will appear on the form using the top left hand corne
36. are met Example 1 Declare the integer variables to hold the values used within this procedure Dim intYearBorn As Integer This information is taken from user entry into the text box Dim intThisYear As Integer This information will be the current year based on system date Dim intYearDifference As Integer This information will be calculated within the procedure intYearBorn txtYearBorn Text Get the value entered in the text box into an integer variable intThisYear Now Year Take the Year part of the current date time and store Now subtract the year born from the current year and store in the integer variable intYearDifference intThisYear intYearBorn Using Select Case work on the value stored in the integer variable calculated above Select Case intYearDifference Use the range aspect of Case to look at the value in intYearDifference and display a message accordingly Case To 11 lblOutcome Text Age at December 31st will be less than 12 Case 12 To 19 lblOutcome Text Age at December 31st will be less than 20 Case 20 To 29 lblOutcome Text Age at December 31st will be less than 30 Case 30 To 39 lblOutcome Text Age at December 31st will be less than 40 Case 40 To 49 lblOutcome Text Age at December 31st will be less than 50 Case Is gt 49 lblOutcome Text Age at December 31st will be 50 or over End Select Example 2 The user will enter a grade P M or D
37. be used by the user at this particular time l The stage of the software design life cycle that involves the programmer writing either Documentation i technical documentation or user documentation Fllinses The name of the three little dots that appear on some properties seen within the p Properties Window Clicking on the ellipses will generate a Dialog Box Enabled A control that is enabled is one that has not been deactivated by the programmer at this particular time Either generated by the compiler after compilation or during coding showing errors made by the programmer or messages coded by the programmer to tell the user that they have done something wrong Every object control has a number of events that can be selected and programmed at Event design time Each type of object has a default event for example a button object s default is the Click event Event handler The type of event selected for any given control such as the _Click event of a button The window that holds all of the controls that are displayed to the user as a screen Form This is the main component of most programming languages especially visual programming The square box shapes that are spaced around the edges of a control to indicate that it is possible to resize this control To enlarge or shrink the control click on it to make it the active control the grab handles will become visible when the control is active and Grab handles then clic
38. become white and the text colour should be black This requires you to access the ForeColor and BackColor properties of the label on the click event of btnWhite When the user clicks btnGreen the background of lblMessage should become green and the text colour should be white This requires you to access the ForeColor and BackColor properties of the label on the click event of btnGreen When the user clicks btnClose the program should close You should make sure that your program is commented and save it in a brand new folder within your Week 01 folder ee eee 114 Jane Fletcher South Nottingham College oS SS a a a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 2 Using Labels Buttons and TextBoxes j Lecturer Jane Fletcher 2 0 Specification for program developed in class Enter your name lbIMessage GroupBox2 f Display btnDisplay MESSsage MESsage A program is needed to meet the following requirements Upon first load all objects on the form should be visible and the cursor should be flashing in txtName When the user clicks btnDisplay the name entered into txtName should be displayed along with the message welcome to programming in lblMessage When the user clicks btnRemove lblMessage should blanked out the text in txtName should be remove
39. before continuing MsgBoxStyle Critical ERROR txtPrice Focus Exit Sub End If If txtPrice Text Length gt 5 Then MsgBox You must enter a price in the range of 1 to 999 99 MsgBoxStyle Critical _ ERROR txtPrice Text txtPrice Focus Exit Sub End If If Not IsNumeric txtPrice Text Then MsgBox You must enter a price in the range of 1 to 999 99 MsgBoxStyle Critical _ ERROR D 04 Jane Fletcher South Nottingham College y aae Unit 14 Event Driven Programming edexce l SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes Lecturer Jane Fletcher txtPrice Text txtPrice Focus Exit Sub End If Dim decPrice As Decimal decPrice txtPrice Text If decPrice lt 01 Or decPrice gt 999 99 Then MsgBox You must enter a price in the range of 1 to 999 99 MsgBoxStyle Critical _ ERROR txtPrice Text txtPrice Focus Exit Sub End If lstCatalogue Items Add String Format MyFormat txtProduct Text Format decPrice _ Currency txtProduct Text txtPrice Text txtProduct Focus End Sub Private Sub btnDeleteSelected Click sender As System Object e As System EventArgs _ Handles btnDeleteSelected Click Check to make sure that the user has selected something from the list box If lstCatalogue SelectedIndex 1 Then MsgBox Yo
40. by the user Examine the contents of the two text boxes by looking at the text property of each If txtFirstNumber Text gt txtSecondNumber Text Then This means that the first number entered is highest lblOutcome Text First number entered is highest Else This means that the first number entered isn t highest lblOutcome Text First number entered is not highest End If If Then Elself Elself End If This is a more complex example of the If statement and can be used with as many Elselfs as necessary It works in exactly the same way as other If statements but with the additional facility of being able to drill down as specifically as necessary to give a more detailed analysis of the data entered by the user or the contents of variables etc When using the Elself it is necessary to specify another comparison it doesn t need to use the Same comparators or logical operators as the initial If statement whereas the Else does not Once a condition has been fulfilled the rest of the Elselfs are ignored and control is passed to the statement after End If In the example below we perform a more detailed analysis of the information input into txtFirstNumber and txtSecondNumber Examine the contents of the two text boxes by looking at the text property of each If txtFirstNumber Text gt txtSecondNumber Text Then This means that the first number entered is highest lblOutcome Text First number entered is h
41. completed exercises ae Lecturer Jane Fletcher This section is to enable you to keep a record of each of the exercises in this book You will be directed by your lecturer when you should be doing them but you must make sure that you keep up to date because if you don t you are going to struggle with the final assignment The key thing with programming is practice practice PRACTICE But even more importantly ENJOY IT ay 2 lt Cs S S C C C C C 37 Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 3 Log of completed exercises Lecturer Jane Fletcher LOG OF PROGRAMMING EXERCISES Date Date 2 Started Finished Checked Comments Program 1 0 Done in class 1 1 Exercise 1 2 0 Done in class 2 1 Exercise 1 3 0 Done in class 3 1 Exercise 1 3 2 Exercise 2 4 0 Done in class 4 1 Exercise 1 4 2 Exercise 2 5 0 Done in class 5 1 Exercise 1 5 2 Exercise 2 6 0 Done in class 6 1 Exercise 1 7 0 Done in class 7 1 Exercise 1 8 0 Done in class 8 1 Exercise 1 8 2 Exercise 2 9 0 Done in class 9 1 Exercise 1 10 0 Done in class 10 1 Exercise 1 11 0 Done in class 11 1 Exercise 1 12 0 Done in class 12 1 Exercise 1 13 0 Done in class 13 1 Exercise 1 14 0 Done in class 14 1 Exercise 1 15 0
42. down to the bottom of gblnvoiceDate should be visible Upon the Form_Load event set the background colour of the menustrip to be white and the foreground to be black The font of the menu strip should be the same as the font on the form The menu strip should have two items at the top level File and Help File should contain two items New Invoice and Close Close should close the program New Invoice should reset the form to its original condition the form should show only gbInvoiceDate and the value of the date in dtpDueDate should be set to today s date All labels and text boxes should be initialised 10 Help should display either a new form or a new label explaining how to use the program There should be a facility to return to the main form 11 On the Form_Load event the correct name of the day should be determined and displayed in lblDate as follows LJ N SO DONO lb1Date Text Today s date amp _ WeekdayName 1 FirstDayOfWeek System amp amp dtTodaysDate 12 On the CloseUp event of dtpDueDate e the date value of the DateTimePicker should be stored in dtlInvoiceDate and the form should be enlarged to display gbInvoiceAmount e The date stored in dtInvoiceDate should be displayed in lblSelectedDate e The difference between the selected due date and today s date should be determined by using a DateDiff operation in the following format D a eee 68 Jane Fletcher South Nottingham Col
43. example to get a user to click on a label when they wish to get the software to perform some sort of processing Form vb Design gt E In order to get a label onto your form click on the Label control in the Toolbox move across to the form and where you wish the label to be drop it If you want a larger label that will enable text to wrap and one that will always be a certain size ean regardless of its contents then drag the cursor to be the size that you require The label will shrink back to enable just the name of the label default name being Label1 then Label2 etc Labell System Windows Forms Label ekek _ When you enter text into the label via the Text property in the ie a e e e e Location 12 18 Properties Window it will stretch to accommodate the new words Locked Fae POM YO L esgn Ae Peteceteteeeiieiiiieiiey per a Modifier Friend acces ee Heenan Padding 0 0 0 0 cc 115 13 Tablnd 0 Now the label will grow Now the label will gro i TextAlign TopLeft UseCompatibleT extRenderi False In order to allow the label to be the size you require you must set the AutoSize property to be False in the Properties Window H Formi le ame Labell The result of doing this is got smisen j AcoessbieRae Defaut i alse a E Ee Oo nchor Top Left False Cantral Now you can alter the BorderStyle property in the Properties Window to find a layout that you like the look of The image ab
44. for IT Practitioners Software Development advancing learning changing lives Commonly used controls Revision questions Exercise 5 Lecturer Jane Fletcher 1 What is the prefix for a check box 2 What is the default event for a check box 3 What values can be contained in a variable of the type string 4 What validation can be used on a text box that should contain string input 5 Is it possible to put a combination of check boxes and radio buttons into one group box and still have the radio buttons work together properly 6 Give three different ways of getting user input 7 Write the concatenation statement to put together the following the contents of the text box txtForename together with the text box txtSurname followed by the literal lives in Nottingham Into the variable strStudentInformation 8 What is the meaning of the word literal in a programming context 9 For which programs written in this unit should you create design documentation such as form dictionaries 10 What is the most difficult program you have written so far Why aal 4 9 Jane Fletcher South Nottingham College p aaa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Revision questions Exercise 6 Lecturer Jane Fletcher 1 Name three objects that could be used to
45. for schools during Apprenticeship Week 6 10 Feb 2012 click here for details perm 2 MenuStript Filey 3 BackToolStripMenultem Back 4 ___ ForwardToolStripnenuitem Forward 5 ExitToolStripMenuitemn Exit e labett TRAINING PROVIDER OF THE YEAR Vacancies Search for a Course Advanced Search Taster Events 2011 12 j L edexcel 5 1 a a advancing learning changing lives Lecturer Jane Fletcher Search Accessibility ContactUs International Login SNC phys of South Nottingham College 25 Have a look atthe taster events available this year Read More More Find us on Facebook AxisCentre 7 nM 184 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 11 Creating Web Browsers m Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to create the very simplest of web browsers 1 In design mode set the Url property of wbWebBrowser to www snc ac uk 2 When the program loads the entire form should be visible The web browser itself should stretch across the entire screen regardless of the size of that screen The code for this which should be placed in the form load event is Dim S
46. has actually been entered Length 0 That not too much data has been entered Length gt That data is of the appropriate type numeric string etc That numeric data is within the valid range This list is by no means exhaustive but is more the minimum testing that you should perform After you ve tested that input is valid you must check that it has been processed correctly by the project This is most usually done by examining the output from the project output can be displayed within a form printed in a report stored within a file or database or a combination of each of these Robust testing must be planned in a considered and structured way The method you will use in this unit is to draw up a table with each input having a column within the table detailing the input you will make Designing structured test data 1 In the table below the column headed Test Num is purely the sequential number of the test and will start at 1 and end once you ve covered every test 2 The next columns should contain details of the input into each of the objects on the form 3 The next column should be the group number or name for this test or these tests The basic aspect of testing see above would cover all the does it load type testing Group 1 might be where you enter numbers into two text boxes for example entering 5 into txtFirstNum and 6 into txtSecondNum does lblAnswer display 11 Group 2 might be
47. into the text box which will then be transferred to the variable chrGrade This input will then be examined in a Select Case and an appropriate message displayed dependent on value Dim chrGrade As Char Holds the user s entry after input and assignment Move the value entered by the user after it has been converted to uppercase D a ee Jane Fletcher South Nottingham College y aaee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures chrGrade StrConv txtGrade Text VbStrConv Uppercase Lecturer Jane Fletcher Using the Select Case statement output a message depending on the value stored within chrGrade Select Case chrGrade Case P lblOutcome Text The grade achieved is a Pass Case M lblOutcome Text The grade achieved is a Merit Case D lblOutcome Text The grade achieved is a Distinction Case Else lblOutcome Text No grade has been achieved End Select Iteration Within the programming context the word iteration can be translated as repetition There are various types of iteration constructs available and which one you choose to use will depend on the type of repetition you need You know exactly how many types you want to loop so you will use For Next e You want to loop for a certain number of times once for each occurrence of a pa
48. measurement is the pixel Sorted The default value for this property is False This means that the Items collection will appear in the order in which they were written in the ListBox If the property is changed to True then the Items will display in alphabetical order with any item beginning with a number will appear before any item beginning with a letter TabIndex Unless the label is to receive control during run time then the programmer can manually alter the Tablndex to be a high number using the Properties Window at design time Visible Set to either True or False determines whether the ListBox is visible or not Can be changed at either design time or run time eH S eee 9 Jane Fletcher South Nottingham College p lt Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls MenuStrip control Lecturer Jane Fletcher MenuStrip The MenuStrip control is accessed via the Menus amp Toolbars collection in the Toolbox by clicking on the icon shown here Once you have clicked on the MenuStrip object move across to the form and left click anywhere on the Form object The MenuStrip will appear at the top of the Form object as shown here You will also be able to see the MenuStrip icon in IE ToolStiipContaines the lower grey pane of the Form object in a similar p
49. month name in the rolled down calendar at run time CalendarTrailingForeColor The colour of the dates of the preceding and following months that appear in the current month s rolled down calendar at run time MaxDate The maximum date that will be displayed in the DateTimePicker at run time If this date is within the current month then any dates after that will not be displayed in the rolled down calendar MinDate The minimum date that will be displayed in the DateTimePicker at run time If this date is within the current month then any dates before that will not be displayed in the rolled down calendar Value The selected date in the DateTimePicker control at run time The format of this value field is m m dd yyyy hh mm ss The default for the time aspect of this value is 00 00 00 If the month number is a single digit figure January through to September for example then there is no leading zero ea D 34 Jane Fletcher South Nottingham College p So Unit 14 Event Driven Programming edexce l SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls PictureBox control Lecturer Jane Fletcher Pi ct u re Box All Windows Forms The PictureBox control is accessed from the Common Controls section of the o Toolbox by clicking on the icon shown here Pointer Button CheckBox CheckedListBox The way to get a Pictu
50. of Choice E scesle 1 and Choice 2 In the Appearance part of the r properties change TabPage1 s Text property to Choice ee 1 Then within the Design section of the Properties ae window change the Name property to tbChoice1 The fencer Morna result of taking this meemsss JE sas C Remove Tot Tabaget course of action is a 5 Eee eee shown in the BE Eo illustration to the _ storey right Notice that on the left hand side the first page 0 is now called tbChoice1 and the Text property will display Choice 1 One thing to be aware of when using TabControls is the fact that you have to make sure that you re selecting the right part of the object when you re double clicking on it to get to the Source Code window Notice the difference between the two images below the first image shows the entire TabControl as being active whereas the second one shows the first TabPage tbChoice1 as being active You will get very different results by clicking on each of these F H 1 TabPage2 me Choice 1 TabPage2 eee te ho m aaa TabControl TabPage active 4 active oY 39 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls TabControl control Lecturer Ja
51. of the TextBox The default background colour is determined by that of the form and it can be changed using the same method as that applied when altering the form s background colour Enabled Default value of True meaning that the TextBox can have user entry when it is the active control on the form A TextBox that is not enabled Enabled property of False will not allow the user to click in the TextBox or the developer to set the focus of the program to the TextBox Font Determines the size style and type of font to be used in the Text property of the TextBox Clicking on the ellipses to the right of the Font property in the Properties Window generates the Font Dialog Box which allows the developer to select his or her choice of font style size ForeColor The colour of the text within the TextBox Unless you change this property the label will have the default foreground colour similar to the Form object Location Where the object will appear on the form using the top left hand corner of the form as a starting point The location is defined using two figures x and y where x is the distance from the left hand margin of the form and y is the distance from the top of the form The default unit of measurement is the pixel one centimetre is approximately 47 pixels Multiline Defaults to False A TextBox with a Multiline property of True will allow the user to type in multiple lines of text into the box Name The
52. question 5 any name as long as it follows all the rules 7 What is the purpose of a program specification 8 Why does a program need design documentation such as form designs and form dictionaries 9 What is the difference between technical documentation such as program specifications and user documentation 10 Give three different ways that a numeric value should be validated a 47 Jane Fletcher South Nottingham College S Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Revision questions Exercise 4 Lecturer Jane Fletcher 1 What is the prefix for a list box 2 What is the difference between a list box and a combo box 3 What Visual Basic NET function would you use to determine whether a particular input contains numbers or not 4 What must you ensure before you execute a lstbox Items RemoveAt command 5 Give two situations where you would use a group box 6 What is the default event for a list box 7 When would that default event be activated 8 What must the last words of any program be 9 What is the purpose of a form dictionary 10 What properties must always be named in a form dictionary aal 4 8 Jane Fletcher South Nottingham College p E Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma
53. showing that RightToLeft No the default value of the DateTimePicker is the current date It is possible Seossso ra to change the default date by altering the Value property in the Properties magnam a0 Window of the control as shown in the illustration to the right Notice that mme o the date has been changed to 20 05 2012 in the Value property and that E ee there is a time aspect to the DateTimePicker s value in addition to the date vawe 20 05 2012 1231 aspect It is important to bear this information in mind when writing code vawe because otherwise unexpected results can occur See later on in this Ms onto document for a further explanation of this You will see that the contents of the Value property has been reflected into the May 2012 Starting display of the DateTimePicker Properties Ix DateTimePickers are the most efficient way of allowing users to enter any date information since it has inbuilt validation and the developer can stipulate the ranges of dates that can be selected either by hard coding dates into the MinDate and MaxDate properties or by coding so that minimum and maximum dates are worked out by comparison to another date for example today s date or somebody s birth date Notice in the illustration to the right that the MinDate and MaxDate properties have a massive range as default which may not be what you want within your software so remember to change them DateTimePickerl System
54. strDay 12 Once the day has been established the present date should be displayed in the label lblTodaysDate in the format strDay amp amp Date Today 13 On the CloseUp event of dtpStartDate the date value of the DateTimePicker should be stored in dtStartDate dtpStartDate should be disabled and dtpEndDate should be enabled 14 The difference between the selected start date and the selected end date should be determined by using a DateDiff operation in the following format ee intDaysDifference DateDiff DateInterval Day dtStartDate dtEndDate where intDaysDifference is declared as a local integer 15 Display the days to Christmas from the selected date in lblMessage in the format The difference between these two dates is as appropriate eee 66 Jane Fletcher South Nottingham College 2_ _ SL SG Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher Exercise 8 2 Jane s sav Discount Rate Discount Amount ee Formt pLabel4 z es i a fabs o 3 NewToolStripMenultem TextBox1 txtInvoiceAmount 4 loseToolStripMenutem 5 HelpTootStripMenultem 6 kabeli ebats tae eee cerns 18 Label7 Label2 Label8 DateTimePicker1 dtpDueDate Label9 Label3 lblSelectedDate Label10 lblDiscountRate Gr
55. that you have to do a little bit more work as below Dim decAnswer As Decimal Select Case intNumberOfDecimalPlaces Case decAnswer decNumber Case 1 decAnswer decNumber 10 Case 2 decAnswer decNumber 100 Case 3 decAnswer decNumber 1000 Case 4 decAnswer decNumber 10000 End Select lstOutput Items Add Or did you mean like this amp decAnswer txtDecimalPlaces Text txtDecimalPlaces Focus End Sub End Class oY 180 Jane Fletcher South Nottingham College ymae ON Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls Lecturer Jane Fletcher Exercise 10 1 Using TabControls 2 eae C Choice 1 Choice ejs 5 intro C Choice3 C Choice4 zj 11 12 13 14 15 o EAN 7 18 Introduction The user has selected tab Object TabPage1 tbintro TabPage2 tbChoice1 TabPage3 tbChoice2 roupBox1 TabPage4 tbChoice3 RadioButton1 radintro TabPage5 tbChoice4 RadioButton2 radChoice1 Label1 on tbChoice1 RadioButton3 radChoice2 Label2 on tbChoice1 RadioButton4 radChoice3 Label3 on tbChoice2 RadioButtond radChoice4 Label4 on tbChoice3 Label5 on tbChoice4 Label6 lblMessage o A 181 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamColl
56. there are some items in the list box by examining the list box s Count property If there is nothing in the list box then the user should be given an appropriate error message via a list box Should there be data in the list box then the user should be asked via a message box if they wish to delete all their catalogue of data If the response is yes then the list box should be cleared of all input In either case the cursor should be returned to txtForename to await user input ce lt lt lt lt lt lt lt lt i SQ C O O OOOOOOOOCCSh SS 208 Jane Fletcher South Nottingham College p Sa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing Lecturer Jane Fletcher 14 0 Specification for program developed in class Using PrintDocument Print Validate Jane Enter your name Jane you are now ready to print Using PrintDocument File Print Preview Print Enter your name Jane Validate Jane you are now ready to print i e lerou 9 TextBoxt Name idate 4 CloseToolStripMenuitem e PreviewToolStripMenuitem ee eses s _SOSOSseesNSeSeS 209 Jane Fletcher South Nottingham College 2_ _ SLS ee SS 4 Unit 14 Event Dr
57. to be able to minimise the form Size The actual dimensions of the form usually defaulting to 300 by 300 measurement unit default being pixels The first figure of the two is the width and the second is the height It is possible to alter these during run time within code StartPosition This property s setting determines where the program will load on the user s screen when it is running The default value of this property is WindowsDefaultLocation which allows the program s form to load anywhere on the user s screen It is far more professional to select CentreScreen for any form which is not either a parent or child form Text The words that appear on the blue bar of the program when it is running WindowState The way in which the form loads The default value is Normal but it is possible to make a form load in maximised or minimised state aay 0 t i i OSOSCOCO SC Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Button control Lecturer Jane Fletcher Button Toolbox E All windows Forms Kon Common Controls The button control is accessed from the Common Controls section of the Toolbox by clicking on the icon shown here It is the second one down after Pointer this order is alphabetical After the Form a
58. to be different to that of the GroupBox it belongs to the label associated with the RadioButton is what will change not the actual dot of the radio button itself Checked Default value is False meaning that the RadioButton is not selected When the user clicks on a deselected RadioButton its Checked property will change to True and vice versa Font Determines the size style and type of font to be used in the Text property of the RadioButton Its default value is to take the Font property of the GroupBox in which it sits Clicking on the ellipses to the right of the Font property in the Properties Window for the RadioButton generates the Font Dialog Box which allows the developer to select his or her choice of font style size ForeColor The colour of the text within the RadioButton s associated label Unless you change this property the label will have the default foreground colour similar to its owning GroupBox object Size Again an x y figure where x is the width of the object and y is the height of the object The unit of measurement is the pixel TabIndex Unless the label is to receive control during run time then the programmer can manually alter the Tablndex to be a high number using the Properties Window at design time Text The writing that appears in the RadioButton s label Normally it will start out with the default name of the RadioButton TextAlign Where the text will appear in the RadioButto
59. underpinning concepts of event driven programming and subsequently to develop particular skills in an event driven language The unit Starts by looking at the features of event driven programming explores the tools and techniques used in their development and takes learners through design and program development Learners will use a structured approach to the design and development of applications ensuring the solution is well documented and tested thoroughly against the original user requirement Event handling features in many languages including Visual Basic Visual Basic for Applications and many other systems e Learning outcomes On completion of this unit a learner should 1 Understand the features of event driven programming 2 Be able to use the tools and techniques of an event driven language 3 Be able to design event driven applications 4 Be able to implement event driven applications Unit content 1 Understand the features of event driven programming Key features service oriented time driven event handlers trigger functions events eg mouse keyboard HTML object form user interface event loops flexibility suitability for graphical interfaces simplicity of programming ease of development Examples operating systems as event driven systems Graphical User Interfaces GUIs Programming languages eg Visual Basic VB Visual Basic for Applications VBA Coldfusion Integrated Development Environments IDEs 2 Be able t
60. user that page comes to the top and becomes active Each of the different tabs act like a separate part of the form despite the fact that they sit on top of each other S 4 Containers hm Pointer _ FlowLayoutPanel The way to get a TabControl object onto your form is to select it from the Containers section of the Toolbox shown here and then move across to the form with it When you reach the place where you want the top left hand corner of the TabControl to be press the left mouse button and drag across and down to describe the size of TabControl that you need Release the left mouse button when you re happy It is possible to resize the TabControl by using the grab handles that are located around the borders of the object m Q m A age TabPage2 GroupBox iojo A Oe a al 4 Menus amp 2bControl Version 4 0 0 0 from Microsoft Corporation R Poi NET Component te Cot Me ke Sta Manages and displays to the user a related collection of tabs that can contain controls and components In the image to the right a TabControl object has been added to a form Notice that there are by default two TabPages within the TabControl Their default names are TabPage1 and TabPagez2 TabControls require drawing using the Drawltem method of the object as shown in the sample code below This TabControl has been called tbMenu in its Name property and the programmer has s
61. user if not If txtInput Text Length Then MsgBox You must enter the price of the item being purchased _ MsgBoxStyle Critical NO INPUT txtInput Focus Put the cursor back into the text box Exit Sub Quit this procedure because user entry is invalid and we can t proceed End If Check that the user han t entered too much input Display a message if they have If txtInput Text Length gt 5 Then MsgBox You must enter a price in the range of 99p to 99 99 _ MsgBoxStyle Critical TOO MUCH INPUT txtInput Text Erase invalid text from the text box C O I S lt _u awinneraheastststststiae 8 Jane Fletcher South Nottingham College a mnm ON Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Validation techniques fp iP YB AZE TZ_A FVCOUeP Lecturer Jane Fletcher txtInput Focus Put the cursor back into the text box Exit Sub Quit this procedure because user entry is invalid and we can t proceed End If Check that the entry made by the user is numeric If it isn t display a message to the user If Not IsNumeric txtInput Text Then MsgBox You must enter a price in the range of 99p to 99 99 _ MsgBoxStyle Critical NON NUMERIC INPUT txtInput Text Erase invalid text from the text box txtInput Focus Put the cursor back into the
62. want the image to appear on the page Dim strImageName As String Application StartupPath Find where the program is stored strimageName striImageName amp maryHadALittleLamb jpg Concatenate the name of the iamge which you have previously stored in the Debug folder of the program e Graphics DrawImageUnscaled Image FromFile strImageName bCorner Draw it End Sub Private Sub btnValidate Click sender As System Object e As System EventArgs _ Handles btnValidate Click Check to see that the user has entered something and that the entry isn t too long If txtName Text Length Then MsgBox You must enter a name before continuing MsgBoxStyle Critical ERROR txtName Focus Exit Sub End If If txtName Text Length gt 20 Then MsgBox You are allowed up to 20 characters for name MsgBoxStyle Critical ERROR txtName Text txtName Focus Exit Sub End If strName txtName Text 213 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing j _ S _ _ _ _ ____ _ Lecturer Jane Fletcher lb1Status Text strName amp you are now ready to print PrintToolStripMenuItem Enabled True End Sub Private Sub NewToolStripMenuItem Click sender As System Object e As Sy
63. 00 00 1 234 567 890 00 1234567890 1234567890 00 1234567890 00 1 234 367 890 00 1234567890 0 1 234 367 890 00 123456789000 0 Process Ze End Button1 btnClear 6 Button2 btnProcess Button3 btnEnd C A 174 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 9 Formatting numbers Lecturer Jane Fletcher A program is needed to meet the following requirements Overview 1 When the program loads the entire form should be visible 2 Throughout the program use the font of your choice except for lstOutput which must have a format of Courier New 3 Upon form load focus should be placed in txtNumber 4 The program needs these variables declared at the top of the program Dim decNumber As Decimal The Clear button should clear the text box list box and put the focus back into txtNumber The End button should close the program btnProcess should work with each input as follows a Input to txtNumber should be validated as being numeric and within the range of 1 to 9 999 999 999 10 significant digits Any illegal input should result in an error message in a message box and the cursor placed back in a blank txtNumber b Valid input in txtNumber should be stored in intNumber c A message to the user should be displa
64. 2 Select Operator Buna Processing Numbers File Help Step 1 Enter number to process Step 2 Select Operator a BE E E Operator selected second GB disabled form enlarged answer shown Instructions on how to continue shown Step 3 Display Answer 10 2 20 00 Go to File and New to continue O SFt lt s s s sONNS aa 92 Jane Fletcher South Nottingham College pame Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Lecturer Jane Fletcher Processing Numbers File Help The purpose of this program is to enter two numbers each of which must be within the range of 1 to 100 then to select an operator to use on these numbers Once you ve clicked on an operator the answer will be displayed About shown Processing Numbers File Help After Return key Step 1 Enter number to process pressed on About screen Step 2 Select Operator Step 3 Display Answer 10 2 20 00 Go to File and New to continue Structured English Form_Load Set the height of Form1 to be 182 Set focus to txtNumber1 End of Form_Load btnProcess_Click If the length of the entry in txtNumber1 0 Then Display a message box saying You must enter a number in the first box Set the cursor focus to txtNumber
65. 25 Within the Font dialog box which appears when you click on the ellipses to the right of the Font property in the Properties Window the developer may select the type the style and the size of the font If you wish the font of an object on the form to be different then set that object s Font property accordingly The rule is that the font of the form is the font of all that form s objects unless they re set differently ForeColor The colour of the writing on the form This property determines the foreground colour of each of the objects on the form unless they re set individually To change the foreground colour use the same method as to change the background colour of an object FormBorderStyle The appearance of the edges of the form The choices are None Fixed Single Fixed3D FixedDialog Sizable FixedToolWindow and SizableToolWindow The default value is Sizeable The best way to find out what the different styles look like is to have a go altering the FormBorderStyle property of a form and having a look at the effect MaximizeBox This property is set to either True or False depending on whether the programmer wants the user to be able to maximise the form Normally it is good practice to take this option away since it makes the software look unprofessional and unbalanced unless the programmer centralises the main pane MinimizeBox This property is set to either True or False depending on whether the programmer wants the user
66. 6 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Design documentation Lecturer Jane Fletcher Form Design Using a text box GroupBox1 txtFirstNumber First Number Second Number GroupBox2 lbIMessage Process btnClose C Form Dictionary Form Control Properties Changeto Used for scope SSS Cd ControtBox False Takes away the close feature font Are Bold Od Foretolor Blak S Size iC SCS IT StartPosition CentreScreen O text usingatextbox SSS J eroupboxt Location 16 12 Grouping user input boxes Se SSCS SOS an Location aAa S Size oa S ext First Number Prompt tothe user abel bocation i385 CSC S sSs s s s S Size os S ooo o Te Second Number Prompt tothe user lll GFKt i s ss sts ie 87 Jane Fletcher South Nottingham College pama 0 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Design documentation Lecturer Jane Fletcher pd TextBox1 BackColor_ White Input of the first number from the _ po ForeColor Black fuser S po ocation 178 40 po Name txtFirstNumber po Se 29 26 po Tabindex O S S
67. 8 27 16 05 2012 08 27 16 05 2012 08 27 16 05 2012 08 27 16 05 2012 08 27 16 05 2012 08 27 16 05 2012 08 26 16 05 2012 08 26 16 05 2012 08 26 16 05 2012 08 26 16 05 2012 08 26 16 05 2012 08 26 16 05 2012 08 25 16 05 2012 08 25 16 05 2012 08 25 16 05 2012 08 25 16 05 2012 08 25 16 05 2012 08 25 Jane Fletcher South Nottingham College File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder File folder Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Creating a folder structure Next here is a screenshot of week 13 of the course Lecturer Jane Fletcher E 14 Event Driven Programming Weekly pro ams gt Week13 e Dw 5 Organize Share with Burn New folder zz Ur Favorites E Name i Date modified Type ae ME Desktop di Exercise done in class 16 05 2012 08 26 File folder P Downloads m Exercise One 16 05 2012 08 26 File folder Recent Places Ji Exercise Two 16 05 2012 08 26 File folder wel 13 Week 13 programming exercise don 29 11 2011 13 20 Microsoft Word O 540 KB Libraries T 13 Week 13 programming exercise don 29 11 2011 13 20 Adobe Acrobat D 189 KE Document
68. 8 as Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons _ VWVYHTHHZCYJY VTH Lecturer Jane Fletcher Once the number has been validated it should be added to lstHistory The text box must be cleared and the cursor must be placed in the text box ready for user entry When the user clicks btnDeleteSelected the program must make sure that the user has actually selected something in lstHistory If they have then that entry should be deleted When the user clicks btnDeleteAll the program must ask the user if they are sure that they wish to delete the entire contents of the list box via a message box If the user answers yes then the contents of the list box must be deleted the contents of the text box deleted and the cursor placed in the box ready for user entry When the user clicks btnClose the entire program should end The program should use an integer variable called intNumber eteNSOEOSsfs S s seFeFe 127 Jane Fletcher South Nottingham College S Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons Lecturer Jane Fletcher Coding for the program Public Cla
69. As Integer For intPointer To lstTitle Items Count 1 lstOrdered Items Add 0 Next Also ensure that no item is selected in the Titles list box by setting its Selectedindex property to 1 6 When the program loads everything should be visible on the form and the background colour of the menu strip set to whatever is used within the program for the background colour of the form 7 The load event of the form should set the background colour of the menu strip to be the same colour as for the form 8 The blu ray titles and prices within lstTitle and lstPrice should be hard coded within their respective Items properties 9 lstRemove should have an equivalent number of hardcoded within its Items property 10 On the Click event of lstTitle a The following code is necessary to ensure that the index of the selected title is retained for use with the other list boxes Work out which blu ray has been selected Dim intPointer As Integer intPointer lstTitle SelectedIndex intPointer now contains the value of where we are at for each of the list boxes in the program b After that the program must query how many of that particular title have already been ordered by looking at the corresponding value in lstOrdered Get how many we had ordered of this blu ray in the first instance Dim intQuantity As Integer intQuantity lstOrdered Items Item intPointer ee eee 5 Jane Fletcher South Notting
70. Box the TextChanged event isn t normally the one that is selected to handle any validation necessary this isn t always the case but in the vast majority of cases it is It is more usual to have a button associated with a group of TextBoxes that will check user entry once it is complete The button will run on the Click event Should you wish to have a TextBox that allows more than one line of user entry then it is necessary to set the Multiline property to True it defaults to False In that way the TextBox can be stretched downwards to accommodate the extra text Properties Tat In the example here TextBox3 has its Multiline property set to True thus allowing the developer Enter chent information Forename TextBoxs System Windows Forms TextEe a MaxLength 32767 a Sumame P MinimumSize 0 o to have a longer TextBox ae Sane bidding oes This is appropriate for a Multiline True field that requires more PasswordChar data to be input by the ReadOnly False user RightToLeFt Mo O FK t SSSS ee 21 Jane Fletcher South Nottingham College pae 64 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls TextBox control Lecturer Jane Fletcher Commonly used properties of the TextBox control BackColor Sets the background colour
71. C Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Form control Lecturer Jane Fletcher In this section we will discuss the most commonly used objects used within this unit and the properties that determine what it looks like and some of the ways in which it will behave Forms One of the most commonly used objects within any visual program is the Form object The Form is the object that holds all the others together and is the one that presents the program image to the user The list of commonly used properties over the page is by no means definitive but is as the title suggests a list of the properties most often changed within a form Below is a blank form in Designer view WindowsApplication1 Microsoft Visual Studio a x File Edit View Project Build Debug Team Data Format Tools Architecture Test Analyze Window Help al a g u dg a Balale2 9 e 2 Bld u a 3 Debug Ol Gg ae A Bes S Toolbox ea Forn1 vb Design X Solution Explorer Ix z EAn O Gla eladasa PEE E Common Controls i i Poi i WindowsApplication1 Z e Pointer am 2 Button EE Form1 vb CheckBox Ba CheckedListBox ene The current A DateTimePicker y Label active form is shown here ListView MaskedT extBox MonthCalendar gt gt Notifylcon NumericUpDown i e O no k Tr r elo Be Ea leh E F ee PictureBox
72. Calculator x Enter 2 numbers First z Second ha oF Pick an action EE C Add Multiply E 10 C Subtract C Divide Answer 2 2 10 o abel 6 TextBox tatSecondNumber 8 GroupBox2 9 RadioButton ada R 10 adioButton2 radSubtract RadioButton3 radMultiply RadioButton4 3 1 Label3 lblAnswer 14 Button2 btnClear eee Jane Fletcher South Nottingham College pae 8 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Lecturer Jane Fletcher A program is needed to meet the following requirements Taking the program written originally in class try entering letters into the text boxes and clicking btnProcess What happens When entering any numeric value into a program it must always be validated The validation necessary is as follows The value must be entered i e there is something there The value must not be too long i e causing an overflow The value must be numeric The value must be in the range specified In this instance the numbers allowed are in the range of 1 to 100 Anything outside that range is invalid Write that validation Tips Ask Google what IsNumeric does in Visual Basic NET Play with the Text Length property of a text box Greater than is writ
73. Click Start the print preview dialog box off in maximised state PrintPreviewDialog1 WindowState FormWindowState Maximized PrintPreviewDialog1 Document PrintDocument1 assign a document to Print Preview control PrintPreviewDialog1 ShowDialog display the PrintPreview dialog box End Sub Private Sub PrintDocumenti1_PrintPage sender As System Object e As _ System Drawing Printing PrintPageEventArgs Handles PrintDocument1 PrintPage Dim MyTitleFont As New Font Courier New 14 FontStyle Underline Dim MyHeaderFont As New Font Courier New 12 FontStyle Italic Dim MyFont As New Font Courier New 12 FontStyle Regular Dim MyFormat As String 25 1 15 2 15 3 15 4 columns Dim intTitlexX intX intY intFontHeight As Integer intTitlexX 175 intX 100 set coordinates for first thing to print intY 5 intFontHeight MyFont GetHeight e Graphics height of 1 line of font used normal font not title font e Graphics DrawString P OE TRY CORNER _ MyTitleFont Brushes Black intTitleX intY Put the title on the page intX 50 This is how far you want to indent from the edge of the page intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer e Graphics DrawString MyFont Brushes Black intX intY Blank line intY intY intFontHeight D Jane Fletcher South Nottingham College pame a Unit 14 E
74. Ctrl K Ctrl B Ts i bs era Make sure that Projects and Solutions is selected in the left Add in Manager hand pane of the subsequent dialog box and within that Macros b ge E Extension Manager enera Dotfuscator Software Services 0 ptions F x Create GUID Error Lookup F gt TaT Projects location ATL MFC Trace Tool FI Proje and wbstaff 03 staff jane fletcherVisual Studio 201 04Projects zl x acai aces 7 ssi User project templates location areca erie are Dee Awhstaff 3 staff jane fletcherWisual Studio 2010 Templates Project e H ernal ools m H Import and Export Settings ie VC Directories User tem templates location Carica WE Project Settings wbstalf 03 statfi jane fletcher Visual Studio 201047 emplates ItemT empl H ee Source Control M Always show Error List if build finishes with errors W Track Active ltem in Solution Explorer Text Editor Debugging Intell Trace Performance Tools Database Tools FH Tools HTML Designer Office Tools Test Tools Test Templating W Show advanced build configurations Always show solution Notice that to the right of the Options list are three combo boxes each with ellipses The top one of these three is headed Projects location Detailed there is the long and f Show al settings Cancel complex path of where projects will be saved for this author on the College network by default It says Save new projects when
75. Done in class 15 1 Exercise 1 16 0 Done in class 16 1 Exercise 1 nee 238 Jane Fletcher South Nottingham College E LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives INDEX Lecturer Jane Fletcher A Addition 72 B Boolean 70 72 73 74 75 156 158 205 208 212 Button i 8 13 14 20 24 50 51 241 Byte 70 C Char 70 79 CheckBox i 8 30 31 Closing ii 66 112 Code 2 7 13 26 30 38 44 49 198 ComboBox i 33 37 38 39 81 Compile 2 Control iii 2 48 95 Crash 2 D Data iii 2 72 96 117 249 Date 70 173 174 175 177 179 253 DateTimePicker ii 8 37 38 39 173 177 179 180 Debugger 2 Decimal 70 86 129 130 158 179 182 183 184 186 190 191 217 238 240 Design iv 2 6 44 61 95 101 109 245 249 Dialog box 2 Disabled 3 Division 72 Documentation 3 245 251 Done in class iv v vi vii 253 254 E editor i 2 4 5 7 48 60 65 67 77 89 Ellipses 3 Enabled 3 14 15 19 20 24 36 42 46 47 89 90 146 148 156 158 159 160 226 230 234 Error messages 3 Event 1 3 49 56 58 63 64 90 93 94 244 247 248 249 Exponentiation 72 F folder structure ii 56 58 Form i 3 8 10 11 13 14 19 22 23 24 34 35 46 48 49 60 61 87 88 95 96 102 103 118 163 173 177 179 248 R st a_OO aa 239 Jane Fletcher So
76. Event Driven Programming Using VB NET edexcel SouthNoitinghamCollege BTEC Extended Diploma for IT Practitioners Software Development lt advancing learning changing lives i First Program Recap of the first lesson but adding a text box Hello From this Ea Remove CLOSE Event Driven Programming Using Visual Basic NET Lecturer Jane Fletcher Hangman R G Bhaji s Speciality Indian Cuisine User1 File Hint File New Order Print Order Drinks e mm To this Pieron meer P N KEKE KI Lager pt 3 uria Ll LL DERE FHE i fE White wine glass A Mineral water 500m1 1 50 Coke 500m1 1 60 Diet Coke 500m1 1 60 ey A LS Ad Ga L BS Q i OWWOWO A Contains alcohol ORDER Onion bhaji 4 60 Starters Vegetable samosa 2 60 Tomato soup 5 20 Close Hint NF NH A Keema Mutter 12 20 JAU E Chicken Jalfrezi 4 90 Vegetable Palak 5 50 Sid Pilau rice 8 00 eA Plain naan 1 80 Keema naan 2 00 Banana Split 3 15 WS Banana Custard 2 80 Malpua 2 50 Lager pt Mineral water 500m1 Coke 500m1 3 4 80 ORDER TOTAL HH PRP Bt H p j 9 00 4 50 Drinks Ww w Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development EG Lecturer Jane Fletcher S ti i lt
77. FirstNumber Text gt txtSecondNumber Text Then This means that the first number entered is highest lblOutcome Text First number entered is highest End If If Then Else End If This is the second least complex of the If statement where if the first condition is not met then the alternative action statements following the Else are performed This differs from the If Then End If since an alternative is offered with the Else that isn t without it If Comparator1 LogicalOperator Comparator 2 Then Actions statements Else Alternative actions statements End If The example code below compares the contents of two text boxes and uses the logical operator greater than If the contents of the first text box is of a higher value than the OCS ai lt i lt i lt i lt i lt i i lt ai lt aiaiaiaiaiaiai lt i lt ize 0 Jane Fletcher South Nottingham College aaee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures Lecturer Jane Fletcher contents of the second box then the condition is met and the first action statement is performed If the contents of the first text box is less than or equal to the contents of the second text box then the second action statement is performed This procedure determines the highest number from a pair entered
78. Fletcher South Nottingham College 2_ _ SL ee SG Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 9 Formatting numbers Lecturer Jane Fletcher Coding for this program Public Class Form2 Dim decNumber As Decimal the holder of the number Dim intNumberOfDecimalPlaces As Integer Private Sub btnEnd Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnEnd Click Stop the project Me Close End Sub Private Sub btnClear_ Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnClear Click Clear out the rubbish lstOutput Items Clear txtNumber Text txtNumber Focus End Sub Private Sub btnProcess Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnProcess Click Take the value entered in the text box validate it and display it in different ways If txtNumber Text Length Then MsgBox You must enter something for number MsgBoxStyle Critical _ No entry made for number txtNumber Focus Exit Sub End If If txtNumber Text Length gt 10 Then MsgBox You have entered too much information in number MsgBoxStyle Critical _ Too long an entry for number txtNumber Text txtNumber Focus Exit Sub End If If Not IsNumeric Val txtNumber Text Then MsgBox You must enter a
79. Font Dialog Box which allows the developer to select his or her choice of font style size ForeColor The colour of the text within the GroupBox Unless you change this property the label will have the default foreground colour similar to the Form object Name The default prefix for a GroupBox control that is to be referred to in the code is gb Size Given as an x y figure where x is the width of the object and y is the height of the object The unit of measurement is the pixel Text The words or numbers that are displayed in the Text property of the GroupBox This text will be displayed in the top left hand corner of the GroupBox Visible Set to either True or False determines whether the GroupBox and all its contents are visible or not Can be changed at either design time or run time Ee CO eee 0 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls TextBox control Lecturer Jane Fletcher TextBox 7 nao The TextBox control is accessed from the Common Controls section of the Toolbox amp reges by clicking on the icon shown here The Common Controls are listed in alphabetical order TextBoxes are used to gain information from the user unlike labels that do not allow user entry at all that is the sole pu
80. G Lecturer Jane Fletcher Topic Page Design documentation 84 Structured English 89 User documentation 98 Testing Projects 106 Example programs 111 1 Using buttons and labels 1 0 Using buttons and labels Done in class 112 1 1 Using buttons and labels Exercise 1 1 114 2 TextBoxes 2 0 Using TextBoxes with buttons and labels Done in class 115 2 1 Using TextBoxes with buttons and labels Exercise 2 1 117 3 RadioButtons 3 0 Using RadioButtons Done in class 118 3 1 Using RadioButtons Exercise 3 1 123 3 2 Using RadioButtons Exercise 3 2 124 4 ListBoxes 4 0 Using ListBoxes Done in class 126 4 1 Using ListBoxes Exercise 4 1 130 4 2 Using ListBoxes Exercise 4 2 132 5 CheckBoxes 5 0 Using CheckBoxes Done in class 134 5 1 Using CheckBoxes Exercise 5 1 139 5 2 Using CheckBoxes Exercise 5 2 141 VA R 111 Jane Fletcher South Nottingham College JE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development _ EG Lecturer Jane Fletcher Topic Page 6 MenuStrips 6 0 Using MenuStrips Done in class 145 6 1 Using MenuStrips Exercise 6 1 150 7 Processing numbers using variables 7 0 Processing numbers using variables Done in class 155 7 1 Processing numbers using variables 7 1 159 8 Using DateTimePickers 8 0 Using DateTimePickers Done in class 161 8 1 Using DateTimePickers Exercise
81. If you are unsure check with your manager toolTip1 SetToolTip Me btnUser3 _ Click here if you have been assigned User Code 3 If you are unsure check with your manager Assigning ToolTip text is time consuming but is extremely useful for assigning onscreen help for the user see the requirements of the P3 criterion of Unit 14 Event Driven Programming Sennen 44 Jane Fletcher South Nottingham College pama a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Revision questions Exercise 1 Lecturer Jane Fletcher 1 What do the initials IDE stand for 2 Within a visual programming environment what does the term object mean 3 Name four different objects that can be put onto a form to help build a graphical user interface 4 What is the Solution Explorer used for 5 What object would you use on a form if its only purpose was to display information to the user 6 What is the default event for a Button object 7 I ve just typed if you want to enter this program what you need to do is to click on the red button that says enter into the Text property of my label All can see on it is if you want to enter th before it all disappears at the edge of the form I ve tried to make my label bigger but it won t grow What have done wrong Tip
82. Jane Fletcher South Nottingham College paee N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to refresh your memory on using listboxes 1 Throughout the program use the font of your choice 2 When the form loads ensure that the background colour of the menustrip is the same as the background colour of the form Place focus in the Product text box 3 Declare one variable at the top of the program Dim MyFormat As String 20 1 15 4 The Close button should close the program 5 Coding for btnAdd a btnAdd should validate user input the text box for product should contain up to 20 characters and must exist The text in price should be numeric and in the range of 0 01 to 999 999 Any erroneous input should result in a message box to the user and the cursor replaced into the correct text box to await further user entry b Declare a local decimal variable for the contents of the price textbox called decPrice The validated input from txtPrice should be stored within that once validated c Once input is valid it should be displayed in the list box using the following statement lstCatalogue Items Add String Format MyF
83. Nottingham College paee N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls DateTimePicker control Lecturer Jane Fletcher DateTimePicker The DateTimePicker control is accessed via the Common Controls section of the Toolbox by clicking on the icon shown here Button CheckBox Bel CheckedListBox TA ComboBox To place a DateTimePicker on your form click on the DateTimePicker icon in F omes D the Toolbox and move across to the form When you re at the place where you i want the top left hand corner of the control to be left click the mouse button and drag across Release the mouse button The resulting DateTimePicker will look very similar to a ComboBox control in that it occupies just one line rather than taking the form of a square box like a ListBox would Notice in the right side of the control there isa mmnm mmaa downward arrow which does nothing when you re in design ig May 2012 mode but during run time this arrowhead will allow the user to view a full month calendar because it will drop down a display which will then rewind once the user has made a change by clicking on a date or by DateTimePicker1 System Windows Form clicking away from the DateTimePicker to anywhere else on the form This 4 4 section of this document was created on May 16 2012 thus
84. O TextBox BackColor White Input of the second number from po ForeColor__ Black the user S o bocation 173 85 S o po Name txtSecondNumber po SIE 29 26 po atin o o GroupBox2 Location 16 173 Grouping together output and po SE 32 155 processing buttons pi habel3 BackColor Red Displaying the output message po Font Arial 16 Bold tothe user o po ForeColor Black o po bocation 18 22 S e po Name tbIMessage po Se 284 o po TextAlign Centre S o pi Button BackColor Black__ __ Vallidates contents of text boxes po Fort Arial 12 Bold _ _and displays the total to the user po ForeColor White Assuming all input is correct po flocatin 102 BF S o po Name tmnProcess oo S y y Oe OD o ext Process o o pi Button2_ BackColor Black Removes the contents of text po Fort Arial 12 Bold boxes and labels _ __ _ _ _ po ForeColor White po oain 102 140 po Name tmRemove PT o T ie SOTS S po ext Remove S o i Button3 BackColor Red Closes the project po Font Arial 12 Bold fp po ForeColor White S O po bocation 245 397 S o po Name tnClose o po Size O po ett lose E Ss Data Dictionary Variable name Type eg Valid range integer string 1 9999 Input from txtFirstNumber intSecondNumber 1 9999 Input from txtSecondNumber intTotal Calculated Calculated by project Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottingha
85. Quit the subroutine End If If the length of the entry in txtNumber1 is gt 3 Then a ss lt a ai OO eS Jane Fletcher South Nottingham College jes_ ____S 60 mu 6 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Lecturer Jane Fletcher Display a messagebox saying You must enter a number in the range of 1 to 100 in the first box Blank out the text in txtNumber1 Set the cursor focus to txtNumber1 Quit the subroutine End If If the entry in txtNumber1 isn t a number Display a messagebox saying You must enter a number in the range of 1 to 100 in the first box Blank out the text in txtNumber Set the cursor focus to txtNumber 1 Quit the subroutine End If Set intNumber1 to hold the value contained in txtNumbert Check the range entered by comparing intNumber1 with 100 and 1 if it is outside that range then Display a messagebox saying You must enter a number in the range of 1 to 100 in the first box Blank out the text in txtNumber Set the cursor focus to txtNumber 1 Quit the subroutine End If Check that there is no decimal place contained in txtNumber if there is then Display a messagebox saying You must enter an integer in the range of 1 to 100 in the first box Blank out the text in txtNumber Set the cursor focus to txtNumber 1 Quit the subr
86. SaveHeight Set the GroupBox gbAbout to invisible End of btnReturn_Click Click event for btnAdd btnMinus btnMultiply and btnDivide Examine the Text property of the sender button i e the button that was clicked by the user If itis Then Add intNumber1 and intNumber2 and store the result in decAnswer If it is Then Subtract intNumber2 from intNumber1 and store the result in decAnswer If it is Then Multiply intNumber1 by intNumber2 and store the result in decAnswer If itis Then Examine the contents of intNumber2 O O O O 96 Jane Fletcher South Nottingham College p manaa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Lecturer Jane Fletcher If it is more than 0 Then Divide intNumber1 by intNumber2 and store the result in decAnswer Otherwise Display an error message and exit the subroutine End Ifs Display the value in decAnswer in the text property of the label l blAnswer along with continuation instructions Set the height of the form to 389 Disable the GroupBox gbOperator End of btnAdd_Click btnMinus_Click btnMultiply_Click and btnDivide_Click ae r TTTCCOCC 97 Jane Fletcher South Nottingham College a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for I
87. T Practitioners Software Development advancing learning changing lives User documentation Lecturer Jane Fletcher You have now heard about design documentation and soon you will hear about robust testing techniques both of these contribute towards what is known as technical documentation Technical documentation is aimed at fellow developers or members of the team who will be responsible for installation and maintenance of your software and as such can contain as much jargon as you feel necessary However you are also responsible for writing what is known as user documentation which is aimed specifically at the user although in many cases developers who are responsible for future project moderation will also read the user documentation that comes with software to get a better feel as to what the purpose of the software is Because it is aimed at the user it must NOT contain jargon and if it is totally unavoidable to include jargon then you should include a glossary of terms at the end User instructions or user manuals to use a different name for the same thing must be stand alone documents complete with cover contents page and lots of illustrations to help you to explain to the user what the software does why it does it and if it is necessary how it does it Your language should be clear and simple and under no circumstances should there be any hint of condescension or bad language the author has been marking student us
88. Text txtForename Focus Exit Sub End If If txtSurname Text Length Then MsgBox You must enter a surname MsgBoxStyle Critical ERROR txtSurname Focus Exit Sub End If If txtSurname Text Length gt 12 Then MsgBox You are allowed up to 12 characters for a surname MsgBoxStyle Critical _ ERROR txtSurname Text txtSurname Focus Exit Sub End If Enable the group box holding the days to work check boxes gbDays Enabled True End Sub Private Sub chkMonday_CheckedChanged ByVal sender As System Object _ ByVal e As System EventArgs Handles chkMonday CheckedChanged Enter the name and day worked into the list box If chkMonday Checked True Then lstHistory Items Add txtForename Text amp amp txtSurname Text amp _ works on Monday eee 36 Jane Fletcher South Nottingham College y aaae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes F Lecturer Jane Fletcher SetListBox End If End Sub Private Sub chkTuesday _CheckedChanged ByVal sender As System Object _ ByVal e As System EventArgs Handles chkTuesday CheckedChanged Enter the name and day worked into the list box If chkTuesday Checked True Then lstHistory Items Add txtForename Text amp amp txtSurname Text amp works on Tuesday SetListBox
89. You should move across to the Solution Explorer window on the right hand side of the form and isha cheat ais on Form1 Lo and Ee ole behold your form will appear in the central pane Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Loading an existing project Lecturer Jane Fletcher Using the Recent Projects list This is this author s least favourite method of opening a project it isn t reliable since it doesn t show the path of where the project is stored For example if you decide that you want to save your project on your pen drive to take home having created it on the College network and saved it on your Z drive you won t know which occurrence of the project is actually being indicated in the list contained in Recent Projects However assuming that you only have one incidence of each of your projects we will proceed with opening a project from the Recent Projects list Open Visual Studio NET using the procedure outlined in pages 54 and 56 The software will load the Start Page for you and your Recent Projects list will be populated Notice in the illustration below that the list has now grown and at the top the project we created in the previous sections appears at the top of the list The most recent project acc
90. You wanted 3 decimal places Your value is 143 456 000 Or did you mean like this 123 456 You wanted 4 decimal places Your value is 123 456 0000 Or did you mean like this 12 3456 Using the Fo rmatNumber state Clear Process Bs End Es Item Object Item Object 6 UstBoxt stOutput 2 label C C E Button2 btnProcess 4 TextBox1 txtNumber Button3 btnEnd 5 fTextBox2 txtDecimalPlaces OOS i lt uaan ee 170 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 9 Formatting numbers lt lt lt lt lt lt _ Lecturer Jane Fletcher A program is needed to meet the following requirements Overview 1 When the program loads the entire form should be visible 2 Throughout the program use the font of your choice 3 Upon form load focus should be placed in txtNumber 4 The program needs these variables declared at the top of the program Dim decNumber As Decimal Dim intNumberOfDecimalPlaces As Integer Dim decAnswer As Decimal 5 The Clear button should clear the text boxes list box and put the focus back into txtNumber 6 The End button should close the program 7 btnProcess should work with each input as follows a Input to txtNumber should be validated as being numeric
91. _ Handles btnUser1 Click btnUser2 Click _ btnUser3 Click btnUser4 Click btnUser5 Click _ btnUser6 Click 7 The buttons btnPass1 btnPass6 will work in a similar fashion as in step 6 For each click of a button the variable strPassword should be concatenated with the sender s text strPassword strPassword amp sender text and the value currently in strPassword should be displayed in lblPassCode 8 When the user clicks btnDone the program should examine the value in intUser and check to see if the correct passcode for that user has been entered using a Select Case statement For user 1 the passcode is 1111 for user 2 it is 2222 and so on a Declare a Boolean variable called bValid b Set the value of bValid to be false c For each case of intUser 1 6 if the passcode entered is correct set bValid to true ee eseseseSeSeFeFeSE 194 Jane Fletcher South Nottingham College aea aa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 12 Creating a Login system Lecturer Jane Fletcher 9 If the user enters a valid passcode i e bValid is True then the program should display Form2 and wait for the user to click that form s Return button If an invalid passcode has been entered then the program must display an error message in the form of a message box 10 The R
92. ___ a0 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls ListBox ComboBox controls Lecturer Jane Fletcher Commonly used Properties of the ListBox control BackColor Sets the background colour of the ListBox The default background colour is determined by that of the form in which it sits but it can be changed using the same method as that applied when altering the form s background colour BorderStyle The default BorderStyle is Fixed3D which means that the ListBox will appear in relief giving a reversed embossed effect Other options are FixedSingle which would give a black line drawn around the edges of the ListBox or None Font Determines the size style and type of font to be used in the Items property of the ListBox Its default value is to take the Font property of form Clicking on the ellipses to the right of the Font property in the Properties Window for the ListBox generates the Font Dialog Box which allows the developer to select his or her choice of font style size ForeColor The colour of the text within the ListBox s Items collection Unless you change this property the label will have the default foreground colour similar to the Form object Size Again an x y figure where x is the width of the object and y is the height of the object The unit of
93. active toolTip1 ShowAlways True Assign the ToolTip to work for the MenuStrip as well also in the Form_Load event MenuStrip1 ShowItemToolTips True OH 43 Jane Fletcher South Nottingham College aee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls ToolTip control Lecturer Jane Fletcher Once the setup has been done by following the statements above the ToolTip is ready to be assigned to each of the objects on the form that you think requires contextual help You do not have to have a ToolTip for each object just the one will do The format of the statement to assign contextual text relate the object to the ToolTip goes as follows NameOfToolTip SetToolTip Me ObjectName Text to display for ObjectName where you replace the NameOfToolTip with the erm name of the ToolTip and ObjectName is the name of the object that requires the contextual help Ensure that you use explicit help and be polite at all times In the example below three buttons representing three different users are assigned to the toolTip1 object again within the Form_Load object toolTip1 SetToolTip Me btnUser1 _ Click here if you have been assigned User Code 1 If you are unsure check with your manager toolTip1 SetToolTip Me btnUser2 _ Click here if you have been assigned User Code 2
94. advancing learning changing lives Example programs 5 Introducing CheckBoxes Lecturer Jane Fletcher If the user selects cappucino put Cappucino into the variable strType The check box for milk should be enabled NOTE THE EXTRA SPACE AFTER THE SELECTED TYPE OF COFFEE IN EACH CASE Shake taste menu If the user selects banana put Banana into the variable strType If the user selects strawberry put Strawberry into the variable strType If the user selects chocolate put Chocolate into the variable strType NOTE THE EXTRA SPACE AFTER THE SELECTED FLAVOUR IN EACH CASE btnUpdateOrder This button will build up the type of drink ordered and all flavours extras etc and display it in the list box lstYourOrder It will then clear everything down so that a new order can be made Once the user clicks btnUpdateOrder move the value that is in strDrink into strOrder like so strOrder strDrink If chkMilk is selected concatenate the value that is in strOrder with the value in strMilk like so strOrder strOrder amp with amp strMilk If chkSugar is selected concatenate the value that is in strOrder with the value in strSugar using the same technique as for chkMilk If chkSweetener is selected concatenate the value that is in strOrder with the value in strSweetener Add the value contained in strOrder into lstYourOrder Then Enable chkMilk disable gbCoffeeType gbExtras a
95. age number entered Number of odds entered Number of evens entered 1 Form 1 2 MenuStrip1 File NewToolStripMenultem CloseToolStripMenultem GroupBox1 TextBox1 txtNumber Button1 btnClickMe 8 GroupBox2 ListBox1 lstNumbers mo label Jane Fletcher South Nottingham College Lecturer Jane Fletcher Label9 lblHighest Label10 lblTotal Label11 lblCount Label12 lblAverage Label13 lblOdds Label14 lblEvens 159 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 7 Number processing with variables f ______ Lecturer Jane Fletcher A program is needed to meet the following requirements 1 The menu strip should have one item at the top level File 2 File should contain two items New and Exit 3 Exit should close the program 4 New should reset the form to its original condition and all variables should be set to their original values 5 When the program loads everything should be visible on the form 6 The program needs these variables seven integers intNumber intCount intTotal intHighest intLowest intOdds and intEvens and a decimal decAverage These should all be declared at the top of the program 7 The value 0 should be stored in intHighest 8 The value 10 000 should be stored in intLowest 9 The cursor should be set
96. al There are no usable controls in wpm this group Drag an item onto oO Visual Stud 1O 2010 Professional this text to add it to the toolbox ra Get Started Guidance and Resources Latest News LJ Connect To Team Foundation Server Welcome Windows Web Cloud Office SharePoint Data a New Project FL Open Project a EE What s New in Visual Studio 2010 Learn about the new features included in this release Recent Projects Visual Studio 2010 Overview j What s New in NET Framework 4 Tal prjPrintingFromAListBox What s New in Visual Basic Customize the Visual Studio Start Page J Close page after project load Creating Applications with Visual Studio J Show page on startup Error List O o Eror A 0 Wamings CD O Messages Description Column Project a Solution Explorer AES Before you can begin to write your first program you have to load the correct editor that you will need in order to create a project that contains Windows forms e e Microsoft Click on New Project O Visual Studio 2010 Professional You will be invited to select from recently accessed templates Geet Started as shown in the illustration below Welcome a ew Project e po i 2 7 Open Project lt D meen Make sure that Visual Basic is selected in the left hand pane Sd E So SM eRe fgg i H anne es The central area of the form shows the different types of SE ae template that
97. al Studio NET supports a range of data types The table below is taken from the Microsoft website and is a list of data types that VB acknowledges runtime type Nominal Value range storage allocation structure Boolean Boolean Depends on True or False implementing platform Char single Char 2 bytes 0 through 65535 unsigned character Date DateTime 8 bytes 0 00 00 midnight on January 1 0001 through 11 59 59 PM on December 31 9999 Decimal Decimal 16 bytes O through 79 228 162 514 264 337 593 543 950 335 7 9 E 28 with no decimal point 0 through 7 9228162514264337593543950335 with 28 places to the right of the decimal smallest nonzero number is 0 Q000000000000000000000000001 1E 28 Double Double 8 bytes 1 79769313486231570E 308 through 4 94065645841246544E 324 double for negative values precision 4 94065645841246544E 324 through 1 79769313486231570E 308 floating point for positive values Long long Int64 8 bytes 9 223 372 036 854 775 808 through 9 223 372 036 854 775 807 integer 9 2 E 18 signed 4 bytes on 32 bit Any type can be stored in a variable of type Object platform 8 bytes on 64 bit Visual Basic Common type language Object Object class platform Short short Int16 2 bytes 32 768 through 32 767 signed integer Jane Fletcher South Nottingham College 64 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege
98. alled intHistoryCount which is used to keep a score of how many numbers are presently in the list box C O essSseSSSSSEEEMSOC 131 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons Lecturer Jane Fletcher Exercise 4 2 Fl Mini Calculaia x Enter 2 numbers First Second a cr Pick an action 6 C Add Multiply 12 lelet j 10 C Subtract C Divide Answer 9 2 10 GroupBox1 60 TextBox2 txtSecondNumber 8 GrowpBoa 9 RadioButiont fadia ee ee 32 Jane Fletcher South Nottingham College paee O Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons A program is needed to meet the following requirements Taking the program written originally in class during week 3 try entering letters into the text boxes and clicking btnProcess What happens When entering any numeric value into a program it must always be validated The validation necessary is as follows The value must be entered i e there is something there The value must not be too long i e causin
99. ame should start with an upper case letter and subsequent letters should be in lower case No spaces are allowed in variable or object names Numbers are allowed It is good practice to avoid leaving objects with their default names this is sloppy practice if that object is to be referred to within the code If the object is NOT referred to within the code then it is acceptable to keep the default name An example of this would be if a group of objects are clustered within a GroupBox object but that GroupBox itself is not referred to during coding then it may retain its default name of GroupBox1 or GroupBox2 etc The list below contains a list of some of the more commonly used controls their prefixes and some example names Notice that each of the example names follows the rules noted in this section For what the controls actually do see the section of this document that goes into detail for that control The blank lines at the bottom of the list can be used for you to make a note of any other controls that you use together with the correct prefix and an example name Object Example name Tabet fo TblDispayessage GroupBox e gbUserinputSet radltalicized S ls Menustrip m DateTimePicker dtpInvoiceDate TabControl tbStarterMenu imrapsedTime PictureBox pb pbCompanytog PMS msFormMainMenuStrip Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTE
100. and reset it strPassword lblPassCode Text Me Height 151 End Sub End Class FORM2 Public Class Form2 Private Sub Form2_Load ByVal sender As System Object ByVal e As System EventArgs _ Handles MyBase Load MenuStrip1 BackColor Color White End Sub Private Sub ReturnToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles ReturnToolStripMenuItem Click Get rid of this form and return Me Dispose Return End Sub End Class o 197 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 12 Creating a Login system Lecturer Jane Fletcher Exercise 12 1 Making a login screen File File New User Which user are you Enter your pass code Congratulations You are logged in Making a Splash Screen U o 2 es O a eae wee 160 ATG Z 4 CloseTooIStripMenultem Close 6 attont e 19 inom biPasrCode B Button bese ao fom Buttond benserd a ens Button5 btnUser5 23 oe A Button6 btnUser6 Label1 T eee 98 Jane Fletcher South Nottingham College pae a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example prog
101. and within the range of 1 to 9 999 999 999 10 significant digits Any illegal input should result in an error message in a message box and the cursor placed back in a blank txtNumber b Valid input in txtNumber should be stored in intNumber c Input to txtDecimalPlaces should be validated as being numeric and within the range of 0 to 4 Any illegal input should result in an error message in a message box and the cursor placed back in a blank txtDecimalPlaces d Valid input in txtDecimalPlaces should be stored in intNumberOfDecimalPlaces e A message to the user should be displayed in lstOutput in the following format lstOutput Items Add You wanted amp intNumberOfDecimalPlaces amp _ decimal places Your value is amp _ FormatNumber decNumber intNumberOfDecimalPlaces f decAnswer should be calculated using a Select Case based on the value in intNumberOfDecimalPlaces i If itis O then decAnswer decNumber ii If itis 1 then decAnswer decNumber 10 ii If it is 2 then decAnswer decNumber 100 iv If itis 3 then decAnswer decNumber 1000 v If it is 4 then decAnswer decNumber 10000 9 The output should displayed as a message to the user in lstOutput in the following format Py mull o lstOutput Items Add Or did you mean like this amp decAnswer h The text should then be cleared from txtDecimalPlaces and the focus of the cursor put there ee F nee Jane
102. ane Fletcher South Nottingham College y aaee 6 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Lecturer Jane Fletcher b Check to ensure that the user has selected a name in lstName by examining the Selectedindex property of lstName to ensure that it isn t equal to 1 If it is then a message box should be shown with a suitable error message and the subroutine exited If the entry is valid then gbAdd should be set to invisible gbUpdate should be set to be visible and enabled e The position of the selected name should be stored in intPointer an Set the pointer to equal the current place in the list box intPointer lstName SelectedIndex f The selected name should be placed into the text box ready for the user to edit it Put the text to be updated in the text box of the update groupbox txtUpdatedName Text lstName Items Item intPointer g The cursor should be placed in txtUpdatedName h The background colour of btnUpdate should be set to red 10 The click event of btnDone should and in this order a Validate the user s entry in txtUpdatedName in the same way as for txtName Any erroneous input should be identified with a message box and then the text copied back into the text box and the cursor placed into the text box
103. ane Fletcher South Nottingham College ymae ON Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls If txtDecimalPlaces Text Length gt 4 Then MsgBox You can have up to four decimal places MsgBoxStyle Critical _ Too much information in number of decimal places txtDecimalPlaces Text txtDecimalPlaces Focus Exit Sub End If Lecturer Jane Fletcher If Not IsNumeric txtDecimalPlaces Text Then MsgBox You must enter numbers in number of decimal places MsgBoxStyle Critical _ Numbers only please txtDecimalPlaces Text txtDecimalPlaces Focus Exit Sub End If intNumberOfDecimalPlaces txtDecimalPlaces Text If intNumberOfDecimalPlaces lt Or intNumberOfDecimalPlaces gt 4 Then MsgBox You can have from to 4 decimal places MsgBoxStyle Critical _ Value out of the accepted range for decimal places txtDecimalPlaces Text txtDecimalPlaces Focus Exit Sub End If lstOutput Items Add You wanted amp intNumberOfDecimalPlaces amp _ decimal places Your value is amp _ FormatNumber decNumber intNumberOfDecimalPlaces FormatNumber the first number is what you want to display and the second is to how many decimal places However it doesn t move the decimal place within the digits of the first number for
104. arning changing lives Example programs 6 MenuStrips Lecturer Jane Fletcher A program is needed to meet the following requirements A program is required which will allow the user to enter two numbers each of which should be within the range of 1 to 100 After the numbers have been entered and proved valid the user should be allowed to select a mathematical operator or and the resulting calculation should be displayed Variables intNumber1 intNumber2 intSaveHeight and decTotal should be declared at the top of the program An About feature is also required to tell the user how the program functions The program should be internally documented in full Processing Numbers Processing Numbers Help lt q umber to process 1 Process 2 Fie Help Step 1 Enter number to process Start up screen Menu bar 1 Process 2 Processing Numbers Fie Help Step 1 Enter number to process 1 Jan Process 2 Processing Numbers File Help Step 1 Enter number to process 2 J Step 2 Select Operator Bun Processing Numbers File Help Step 1 Enter number to process Step 2 Select Operator Step 3 Display Answer 10 2 20 00 Operator selected second GB disabled form enlarged answer shown Go to File and New to continue Instructions on how to continue shown YF ee 51 Jane Fletcher South Nottingham College oS a 5 Unit 14 Event Driven Programming edexcel
105. ashscreen1 Close the Properties window for the project by clicking on the X button on the Properties top tab SplashScreentv Desian gt M Here is a shot of the design view of the splash screen that has a Tm background image on the form and a label stating that This is a This is a SPLASH SCREEN and a Timer object visible in the lower pane SPLASH SCREEN The Interview property for the Timer is set to 3000 i e three seconds and the Enabled property should be set to True If you want the splash screen to be visible longer make the interval longer ee 82 Jane Fletcher South Nottingham College jes_ ___ab__S aan _ Qo66 aS a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Making a project look more professional Lecturer Jane Fletcher Coding to make the splash screen work is very simple On the Tick event of Timer1 add coding Disable the timer so that multiple occurrences of Form1 don t load Timer1 Enabled False Declare a new instance of Form1 you should use the same name as the form here Dim Form1 As Formi New Form1 Hide the current form SplashScreen1 Me Hide Show Form1 to the user in place of SplashScreentl Form1 ShowDialog Close Form1 Me Close Every programmer develops their preferred method of displaying their splash screens the a
106. at on subsequent loadings of the software it will appear in your list of program favourites when you click your Start button as shown here to the right Once you have clicked Microsoft Visual Studio 2010 the software s splash 5 LY Sticky Notes screen will load shown below 7 Aa p op Paint Q Snipping Tool ses XPS Viewer Si Windows Fax and Scan OP Visual Studio 2010 Professiona m When the software has loaded the first time you run Visual Studio you may be shown a screen that asks you to choose your default environment settings as shown below x Make sure that you select Visual Basic OOD Visual Studio 2010 Utimate Development Settings This is the one circled in fobs is Lea cakes toe aiuto fee sb Gk secs Gy E red rather than the one that is selected in the sevceer ge ogee N Pe onc ane YW Tan illustration shown to the left Once you ve done macnn cuse aT that click the Start Visual Studio button MLCT Ben EMER IG CO d ar arioeaen choose Import and Export Settings and then choose Reset af You will probably not be asked to do this again on a College computer but if you are make sure you always pick Visual Basic Development Settings It isn t the end of the world if you make a mistake eal crete ment Settings thes colection of f deveko in e P A 7 ee Han one propammnganuace so don t panic if that is the case It will mean Web Development Code Ont however that you wil
107. at one is by far the easiest Notice that the Toolbox Properties Window and Solution Explorer remain in the same place They do however look slightly different in each view the properties for an object aren t accessible from the code window for example TIP If you open up a program and your form appears to have vanished you re probably in the Source Code View of the editor Go to the Solution Explorer and click on the name of the form you re wanting to see then click on the View Designer button on the top line of the Solution Explorer Solution Explorer E3 priFirstProgra H Ea My Project H ES Porm vb ne I s s s sesia _ sOS 7 Jane Fletcher South Nottingham College lh Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Naming conventions for objects controls Lecturer Jane Fletcher Within the programming world it has become the custom to name objects controls and variables using a set naming convention This is so that it is possible to tell at a glance when reading code to what type of object or variable that code is processing accessing at that time Most objects and variables have a prefix of three letters each of which are written in lower case The letters that follow should be descriptive of what the object or variable does and each word in the n
108. ation Lecturer Jane Fletcher Exit the subroutine End If If txtSecondNumber s text length gt 4 Then Display message to the user stating that an error has occurred Remove the text from txtSecondNumber Put the focus of the cursor into txtSecondNumber Exit the subroutine End If If txtSecondNumber s text is not numeric Display message to the user stating that an error has occurred Remove the text from txtSecondNumber Put the focus of the cursor into txtSecondNumber Exit the subroutine End If Store the value in the Text property of txtSecondNumber in intSecondNumber If intSecondNumber lt 1 or intSecondNumber gt 9999 Display message to the user stating that an error has occurred Remove the text from txtSecondNumber Remove the text from txtSecondNumber Put the focus of the cursor into txtSecondNumber Exit the subroutine End If Add intFirstNumber and intSecondNumber and store the result in intTotal Display intTotal in lblMessage s text property in the format intFirstNumber intsecondNumber intTotal where the figures appear End Sub Click Event for bthnRemove Clear out txtFirstNumber s text property Clear out txtSecondNumber s text property Clear out the text in lblMessage s text property Set the cursor s focus in txtFirstNumber End Sub Click Event for btnClose Display a messagebox to the user saying Goodbye Close the project End Sub ee TTTT T CLL L 8
109. ber intSecondNumber As Integer Used to store the values from txtFirstNumber and txtSecondNumber Dim intCounter As Integer Used as a counter to see how many times the loop is processed intFirstNumber txtFirstNumber Text Store the input from the user in the integer variable intSecondNumber txtSecondNumber Text This is the value to reach intTotal intFirstNumber Set the total to equal the first number straight away The loop will be performed while the accumulated total of first numbers is less than the second number entered by the user OO Y Ne 5 Jane Fletcher South Nottingham College o_o 6424 a Unit 14 Event Driven Programming edexce l SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures Do While intTotal lt intSecondNumber tntTotal intFirstNumber Add intFirstNumber to the running total tntCounter 1 Add one to the counter Loop Lecturer Jane Fletcher Display the outcome in the label lblOutcome Text The loop was performed amp intCounter amp times i Do While Loop pce Do While Loop Eh Number to add Number to add up to Number to add Number to add up to 5 5 a 33 Process Process The loop was The loop was performed 0 times performed 6 times In the coding below the Do While Loop italicised in the coding above is replaced by a Do Loop Whil
110. ber As Integer Dim intHighest As Integer Private Sub CloseToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles CloseToolStripMenuItem Click End the project End End Sub Private Sub Form1_Load ByVal sender As System Object ByVal e As System EventArgs _ Handles MyBase Load Change the properties of the menustrip MenuStrip1 BackColor Color White MenuStrip1 ForeColor Color Black End Sub Private Sub btnClickMe Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnClickMe Click Validate the number entered If txtNumber Text Length Then MsgBox You must enter a number MsgBoxStyle Critical No input txtNumber Focus Exit Sub End If If txtNumber Text Length gt 4 Then MsgBox You have entered too much information MsgBoxStyle Critical _ Too much input txtNumber Text txtNumber Focus Exit Sub End If If Not IsNumeric txtNumber Text Then MsgBox You must enter a number in the range of 1 to 9999 MsgBoxStyle Critical _ You must enter a number in the right range txtNumber Text txtNumber Focus Exit Sub End If intNumber txtNumber Text If intNumber lt 1 Or intNumber gt 9999 Then MsgBox You must enter a number in the range of 1 to 9999 MsgBoxStyle Critical _ You must enter a number in the right range txtNumber Text txtNumber Focus Exit Sub a a ee 57 Jane Fletcher South Notting
111. ber in the range of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine End If If the entry in txtNumber2 isn t a number Display a messagebox saying You must enter a number in the range of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine End If Set intNumber2 to hold the value contained in txtNumber2 Check the range entered by comparing intNumber2 with 100 and 1 if it is outside that range then Display a messagebox saying You must enter a number in the range of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine End If Check that there is no decimal place contained in txtNumber2 if there is then Display a messagebox saying You must enter an integer in the range of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine End If Set the height of the form to be 284 Bring the group box gbOperator to the front Disable the group box gbNumbers End of btnProcess_Click ce lt i ia SS UC s sSsS CCVCOVLG 153 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advanci
112. bove is the author s personal favourite Play around with the coding above and develop a method you like Using the MenuStrip control One thing that all users of computer software are accustomed to is the MenuStrip They may not know it as such but they have been conditioned to expect to see File Edit View and so on reading from the left on the top active row of any software they use Remember the fuss when Microsoft brought out Office 2007 and the familiar menu bar was replaced by the Ribbon People do not take kindly to change so bear this in mind when you are writing your programs The MenuStrip object see page 30 is a very easy way to make your project look more professional as long as you use it responsibly and professionally and stick to commonly used protocol when you design the layout of the menu Users like the familiar and hate change this is a very important point to take into consideration when you re putting together your own software R G Bhaji s Speciality Indian Cuisine Here to the right is an example of a MenuStrip in use in a Ue NewOrdel Bint order piece of software created by this author Note the fact that some items are enabled and some aren t when the Exit Enabled property is set to False the item appears greyed out as the Logout New Order and Print Order items are here Click here to log in Notice also the fact that the
113. cing learning changing lives Arithmetic and logical operators Lecturer Jane Fletcher If the user enters 10 into the first text box txtFirstNumber and 5 into the second text box txtSecondNumber then the first condition is not met and so the And operator will return False If the user enters 5 into both text boxes the And operator will return True Or The Or operator performs logical disjunction or inclusion on two Boolean expressions If either expression evaluates to True or both evaluate to True then Or returns True If neither expression evaluates to True Or returns False If txtFirstNumber Text lt 10 Or txtSecondNumber Text lt 10 Then lblOutcome Text One input is less than 10 End If If the user enters 5 into txtFirstNumber and 10 into txtSecondNumber the Or operator returns True because one of the conditions is met If the user enters 5 into both text boxes the Or operator returns True because at least one of the conditions is met If the user enters 10 into both text boxes the Or operator will return False because neither condition is met Xor The Xor operator performs logical exclusion on two Boolean expressions If exactly one expression evaluates to True but not both Xor returns True If both expressions evaluate to True or both evaluate to False Xor returns False If txtFirstNumber Text lt 10 Xor txtSecondNumber Text lt 10 Then lblOutcome Text One input is less than 10 End If If the
114. ck for a history wbWebBrowser GoBack 9 The Home button should move the browser to the home url of www snc ac uk wobWebBrowser Navigate www snc ac uk 10 The processing for btnGo is as follows q Firstly ensure that the user has entered something by checking the length property of the text box txtWebAddress If the length is 0 then the subroutine should show an error message via a message box and exit with no further processing r Declare a string variable called strWebAddress s Move the contents of text property of txtWebAddress to strWebAddress t Change the contents of the variable strWebAddress to lower case StrWebAddress LCase strWebAddress u Declare a string variable called strPrefix v Determine the first four characters in the variable strWebAddress to ensure that the user has entered www strPrefix Mid strWebAddress 1 4 w Look at the contents of strPrefix If it is NOT equal to www then concatenate www onto the front of strWebAddress If strPrefix www Then Else strwWebAddress www amp strWebAddress End If x Navigate to the webpage indicated in strWebAddress wobWebBrowser Navigate strWebAddress 11 The Navigated event of the web browser should display the title of the web document being displayed in the Text property of the form Me Text wbWebBrowser DocumentTitle ToString 12 The Navigating event of the web browser should di
115. cond Pick an action cz C Add Multiply 10 C Subtract C Divide ho i o j a Answer 9 2 10 rem 2 GroupBoxt 3 abet C 6 ___TextBoxz tSecondNumber eo o ooa o o fadiobuttont radAdd 0 RadioButton radSubtract RadioButton3 edna RadioButton4 e Label3 lblAnswer 1400 Button2 btnClear ee ee ee 8 Jane Fletcher South Nottingham College paee 6 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Lecturer Jane Fletcher A program is needed to meet the following requirements When the program loads the height of the form should be set so that only the first group box GroupBox1 is visible Once the user has entered numbers into both text boxes and clicked btnContinue the form s height should increase to show GroupBox2 Once the user has selected one of the radio buttons the form s height should increase to show everything including btnClear At the top of the program after the Public Class declare three variables like so Dim intFirstNumber intSecondNumber As Integer Dim decTotal As Decimal The coding should assign the value that is contained in txtFirstNumber into intFirstNumber like SO intFirstNumber txtFirstNumber Text and then perform a similar operation for the value in txtSecondNumber
116. created IY Warn user when the project location ig not trusted Show Output window when build starts Prompt for symbolic renaming when renaming files wbstaff 03 staff jane fletcher Visual Studio 2010 Projects This is to be changed to enable saving to take place in the Unit 14 Event Driven Programming and Weekly Programs folders My Videos NLP Personal E G SecheneNET Click on the ellipses to the right of the named project location The Project C SMART Notebook O SMART Technologies Location dialog box will open shown on the right E A e E Visual Studio 2010 H O Backup Files Code Snippets Notice that the default saving location has been set at a path of O MA i Folder Poets My Documents gt Visual Studio 2010 gt Projects me cee Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Saving a project Lecturer Jane Fletcher Click on the folder that you made earlier ae cs 7 amp Environmen Siemens 66 U n j t 1 4 _ Eve n t D ri ve n P rog ra m m n g 39 t h e n p zo Solutions wbstaff O3 staff jane fletcher Unit 14 Event Driven Programmings We e bc enera Use TT wa TE Weekly Programs then click on the OK oo CENAN ECEE eI C Directories YC Pr
117. creen Bounds Height Dim intWidth intHeight As Integer intWidth Screen PrimaryScreen Bounds Width intHeight Screen PrimaryScreen Bounds Height wbWebBrowser Left 20 wbWebBrowser Width intWidth 40 woWebBrowser Height intHeight 150 4 Also in form load allocate the tool tips to the objects on the form that require them Me ttWebBrowserBits ShowAlways True Me ttWebBrowserBits ReshowDelay 10 Me ttWebBrowserBits AutomaticDelay 100 ttwWebBrowserBits SetToolTip btnBack Back ttWebBrowserBits SetToolTip btnForward Forward ttWebBrowserBits SetToolTip btnStop Stop ttWebBrowserBits SetToolTip btnRefresh Refresh ttWebBrowserBits SetToolTip btnHome Home ttWebBrowserBits SetToolTip txtWebAddress Enter Web Address 5 Throughout the program use the font of your choice 6 The Exit button should close the program 7 The Forward button should move the browser on to the last website accessed should the Back button have been pressed You do not have to check for a history wbWebBrowser GoForward eg 90 Jane Fletcher South Nottingham College pae O Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 11 Creating Web Browsers Lecturer Jane Fletcher 8 The Back button should move the browser to the previous website accessed You do not have to che
118. creenSize As Size New Size Screen PrimaryScreen Bounds Width _ Screen PrimaryScreen Bounds Height Dim intWidth intHeight As Integer intWidth Screen PrimaryScreen Bounds Width intHeight Screen PrimaryScreen Bounds Height wbWebBrowser Left 20 wbWebBrowser Width intWidth 40 woWebBrowser Height intHeight 150 3 Throughout the program use the font of your choice 4 The Exit button should close the program 5 The Forward button should move the browser on to the last website accessed should the Back button have been pressed You do not have to check for a history wbWebBrowser GoForward 6 The Back button should move the browser to the previous website accessed You do not have to check for a history wbWebBrowser GoBack 7 The processing for btnGo is as follows i Firstly ensure that the user has entered something by checking the length property of the text box txtAddress If the length is 0 then the subrouting should be exited with no further processing Declare a string variable called strAddress Move the contents of text property of txtAddress to strAddress Change the contents of the variable strAddress to lower case strAddress LCase strAddress m Declare a string variable called strFrontBit 185 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advanc
119. d e Put yourself in the shoes of your users when you re read your user documentation Let somebody else read your instructions before you publish so that you can get somebody else s opinion on your writing e Never EVER under ANY circumstances should you refer to Visual Basic NET or programming or editors since this is likely to send the user screaming and running for the hills e Your user instructions should be a stand alone document Following on in this section is an example user manual for the software detailed in the section Design documentation It does not have a front cover contents page and separate page numbers but the instructions are what counts here ae a O OOOOON 99 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives User documentation Lecturer Jane Fletcher Introduction Welcome to the TwoPlusTwo software from SNC PLC You have purchased this software specifically to help you with your business need when it comes to adding up two numbers and displaying a reliable and accurate total You have the facility to add as many pairs of numbers as necessary and you are guaranteed an accurate answer regardless of how many times you use your software Installation The first time you insert the CD into your computer s o
120. d and the cursor should be put into txtName When the user clicks btnClose the program should close Now experiment Put two text boxes on the form forename and surname and concatenate them with a space in between please and display a longer message eG ee 5 Jane Fletcher South Nottingham College paee ON Unit 14 Event Driven Programming edexce l SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 2 Using Labels Buttons and TextBoxes Lecturer Jane Fletcher Coding for the program Public Class Form1 Private Sub btnClose Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnClose Click Close the project down End End Sub Private Sub btnDisplay Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnDisplay Click Concatenate the content of the text box with a message and display it to the user lblMessage Text txtName Text amp welcome to programming End Sub Private Sub btnRemove Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnRemove Click Clear down the message from the label remove the text from the text box and put the focus of the program back into the text box lblMessage Text txtName Text txtName Focus End Sub End Class D 6 Jane Fletcher South Nottingham College 2_ _ SL SS 4
121. d lblMessage displays txtForename and Fletcher Jane Fletcher txtSurname welcome to programming btnDisplay_Click Peter and lblMessage displays txtForename and Rabbit Peter Rabbit txtSurname welcome to programming 10 btnDisplay_Click Peter and lblMessage displays txtForename and Rabbit Peter Rabbit txtSurname welcome to programming btnRemove i Text boxes clear label clears and cursor is placed in txtForename btnClose Click Program closes Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Testing Projects Lecturer Jane Fletcher If the test plan should reveal that there are bugs within the project then you should document those the final column of the plan indicates if the test was successful yes or no so in the case of the test failing you should enter N in this column and go on to explain in a separate document why the test failed and explain what you did to solve the problem You should then repeat the test and any further tests that were affected by the initial failure and document that Below is test number 8 repeated but in this case there is an error Component s tested Expected result Actual result number btnDisplay_Click Jane and lblMessage displays txtForename and Fletcher Jane Fletc
122. d to source control Click on the Save button Once you have done this you can see that your project has assumed its new name by looking in the top left of the NET editor screen as shown to the right E File Edt View TTE Des a d lsaGlals2 9 8 ComboBox A rr _ Now you have saved your project for the first time you need only click on the Save or 4 4 Save AlV icons in the icon bar Save will save the current environment Save All will save all aspects of the project including other forms eS 59 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Closing a project Closing your project is extremely easy all you do is click on top left hand corner of the NET environment edexcel advancing learning changing lives Lecturer Jane Fletcher the cross in the Gem If you have made a change in either design view or coding Microsoft visual Studio BAES view of any of the forms within the project and haven t saved since you will be told by VB NET after you have clicked the close button that you haven t and asked if you would like to save as shown in the illustration to the right If you would like to quit without saving then you should click the No button All changes made since your last save will be lost if you do thi
123. ded Diploma for IT Practitioners Software Development Testing Projects Test Component s tested number Form1_Load Z txtForename click btnDisplay_Click txtForename and btnDisplay_Click and txtForename 7 btnDisplay_Click TabOrder Press Tab key No input into txtForename btnDisplay i Jane and txtSurname 1111111111111 1111111111111 edexcel advancing learning changing lives Lecturer Jane Fletcher result Actual result Form displays correctly Cursor is placed into txtForename on Form_Load Cursor is placed in txtSurname after Tab key pressed Error message to user Stating that there has been no input into txtForename Error message to user Stating that there has been no input into txtSurname Using a text box Error message to the eee user stating that the Pint a entry for pni txtForename is too long 108 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Testing Projects j Lecturer Jane Fletcher Test Component s tested Input Expected result Actual result Yes No number 7 btnDisplay_Click Jane and Error message to the txtForename and 1111111111111 user stating that the txtSurname 1111111111111 entry for txtSurname is too long btnDisplay_Click Jane an
124. ded Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 2 Glossary of Terms Term Definition Tools and techniques Tool boxes and controls Selection Loops Event handlers Triggers Objects Object properties Menus Debugging tools Variables Declaration name type Scope Constants Data types LO 3 Be able to design event driven applications Specification Input Output Processes User need Purpose Lecturer Jane Fletcher Selecting and assigning properties Data storage Event procedures LO 4 Be able to implement event driven applications Creation of application IDE Debugging how Data validation what and how Error handling and reporting what and how 2 WwW O1 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 2 Glossary of Terms Lecturer Jane Fletcher Term Construct definition Construct examples User D Technical E GENERAL for your use FF lt i O SCS Sa HS 36 Jane Fletcher South Nottingham College JE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 3 Log of
125. default prefix for the TextBox object is txt Size Again an x y figure where x is the width of the object and y is the height of the object The unit of measurement is the pixel Unless Multiline is set to True the height of the box cannot be altered the height is determined by the size of the box s Font property TabIndex Unless the label is to receive control during run time then the programmer can manually alter the Tablndex to be a high number using the Properties Window at design time See the explanation of the purpose of the Tablndex in the Button object Text The writing that appears in the box Normally it will start out blank although default text can be put in the box s Text property at run time by the software TextAlign Where the text will appear in the TextBox The default value is Left but Centre and Right are also available YG _ t lt lt lt lt za ee Jane Fletcher South Nottingham College lt C aaaaaaa a aS ee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls TextBox control Lecturer Jane Fletcher Visible Set to either True or False determines whether the TextBox is visible or not Can be changed at either design time or run time WordWrap Default value is True If the Mu
126. difference between the MenuStrip object and many other objects is that the MenuStrip can have many Click events one per lowest level item By lowest level in this context we mean items that do not have items of their own In the example above the File menu item owns New and Close so that when File is clicked the event opens the sub menu that includes New and Close without any coding being required from the developer New and Close don t have any sub menus so they will have Click events of their own available to the developer to implement by double clicking on them in design view Below is the coding for the Close event of the example above Private Sub CloseToolStripMenuItem Click ByVal sender As System Object ByVal e As System EventArgs _ Handles CloseToolStripMenuItem Click Close the current project End End Sub Note that the underscore character included in the Private Sub statement indicates that the Statement is continued on the line below The underscore must be preceded by a space otherwise it will not be acknowledged and a compiler error will be generated ltems on the MenuStrip control can be enabled or disabled at both design and run time depending on logical need Items that have their Enabled property set to False will appear greyed out at run time eK t lt lt i i i s w w SOSOS 31 Jane Fletcher South
127. dio editor 6 Naming conventions for objects controls 8 Commonly used controls Form 9 Button 12 Label 15 GroupBox 19 TextBox 21 RadioButton 24 CheckBox 26 ListBox ComboBox 28 MenuStrip 30 DateTimePicker 32 PictureBox 35 TabControl 38 Timer 41 ToolTip 43 Revision questions 45 Creating a folder structure 51 Starting a new Project 54 DUU r CSOeSSHE SNs i i i i i i i i i i i i i i i i i i i i i i aw Jane Fletcher South Nottingham College pana NO Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development _ So Lecturer Jane Fletcher Topic Page Saving a Project 57 Closing a Project 60 Loading an existing Project 61 Data types 64 Arithmetic and logical operators 66 Control Structures Sequence 69 Selection 70 If Then End If If Then Else End If If Then Elself End If Select Case End Select Iteration 13 For Next For Each Do Until Loop and Do While Loop Do Until Loop Validation techniques 78 Making a Project look more professional SplashScreen 80 MenuStrip control 83 ToolTips control 83 aay 8 Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development _ E
128. e i SS C SsSCOCQH 203 Jane Fletcher South Nottingham College p lt Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes Lecturer Jane Fletcher Coding for this program Public Class Form1 Dim MyFormat As String 20 1 15 Private Sub CloseToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles CloseToolStripMenuItem Click End the project Me Dispose End End Sub Private Sub Form1_Load ByVal sender As System Object ByVal e As System EventArgs _ Handles MyBase Load Set up the defaults of the form MenuStrip1 BackColor Color White End Sub Private Sub btnAdd_Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnAdd Click Perform the usual validation to make sure that user entry is correct If txtProduct Text Length Then MsgBox You must enter a product before continuing MsgBoxStyle Critical ERROR txtProduct Focus Exit Sub End If If txtProduct Text Length gt 20 Then MsgBox You may enter up to 20 characters for product name MsgBoxStyle Critical _ ERROR txtProduct Text txtProduct Focus Exit Sub End If If txtPrice Text Length Then MsgBox You must enter a price
129. e A ListBox on the other hand can be stretched downwards to display the entire list of data contained within it at design time or if that is too much then it will give a vertical scroll bar to the left hand side of the list The user cannot type information into the ListBox control When the user makes a choice from the ListBox s list of items then that line of the list is highlighted but other items on the list still remain visible An example of a ComboBox in action is the URL bar in a web browser An example of a ListBox is the list shown in the Favourites window You can type into one but not the other In the example below you will see that the Items dialog box has had several items added to it by clicking on the ellipses to the right of the Items property You cannot type directly into the Items property itself that displays the word Collection The second illustration shows the same ListBox at run time this is what the user sees when using the program O x Enter the strings in the collection one per line Orange juice Orange juice Grapefruit juice Pineapple juice Notice in the second illustration the vertical scroll bar that the program has automatically generated due to the fact that there are too many items in the list to be displayed in the space available The developer doesn t have to undertake any extra coding to make this happen oo a 8 Jane Fletcher South Nottingham College je_ _ _
130. e Items RemoveAt 1lstName SelectedIndex Put the new item in the old one s place lstName Items Insert intPointer txtUpdatedName Text 222 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Lecturer Jane Fletcher Change the AcceptButton back to btnProcess Me AcceptButton btnProcess gbUpdate Visible False gbAdd Visible True txtName Focus End Sub Private Sub btnRemove Click sender As System Object e As System EventArgs _ Handles btnRemove Click Check to make sure that the user has selected something to delete If lstName SelectedIndex gt 1 Then Else MsgBox You must select a name from the list before continuing _ MsgBoxStyle Critical ERROR Exit Sub End If lstName Items RemoveAt lstName SelectedIndex End Sub Private Sub btnClear_ Click sender As System Object e As System EventArgs _ Handles btnClear Click Check to make sure that this is what the user wants Dim intResponse As Integer intResponse MsgBox Are you sure you want to delete everything _ MsgBoxStyle YesNo Are you sure If intResponse vbYes Then Clear everything down lstName Items Clear MsgBox Everything deleted MsgBoxStyle OkOnl
131. e Opacity Padding RightToLeft RightToLeftLayout False Showlcon True ShowlnTaskbar True Size 300 300 Project SizeGripStyle Auto a StartPosition WindowsDefaultLocat Tag 7 Text Formi Text The text associated with the control Again if you ve made any changes to the project and not saved you ll be prompted as above If you close the project you will be in the NET environment with no active project In the illustration below you can see that the Solution Explorer view on the right hand side of the screen is empty There is no active project eo Microsoft Visual Studio File Edit View Debug Team Data Tools Test Window Help pe g a dg aanlal 2 9 e 2 Bl gt w a A Debug A A a Case BS There are no usable controls in this group Drag an item onto this text to add it to the toolbox Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Loading an existing project Lecturer Jane Fletcher There are several ways to load an existing project From Windows Explorer by clicking on the Solution file of the project By opening Visual Basic NET and using the Recent Projects list on the Start page By opening Visual Basic NET and clicking on Open Project on the Start page By opening Visual Basic NET and clicking File on th
132. e aaee N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Making a project look more professional Lecturer Jane Fletcher Method 2 using the Project menu item An alternative method to add a form to an existing project is to click on Project in the menu bar and from there click on Add Windows Form WindowsApplication1 Microsoft Visual Studio e File Edit View Project Build Debug Team Data Format Tools Test Window Help Sl fF Gg SA 2 3 GS J SS Add Windows Form gt u a S302 Debug pi S Toolbox ee Design x Aan EA OET o Li Tools i Add Component i BEE 4 Data W Add Module From there select Splash Screen from the Add x ot Installed Templates Sort by Default New Item dialog box and then click on the Add A n EE or rorent oom Common tems button From there the steps are exactly the oa E repon oer same as for Method 1 Windows Forms z Report Wizard Common Items Reporting i Workflow E Resources File Common Items WPF 7 Online Templates W Service based Database Common Items Splash Screen Common Items Making a splash screen The template splash screen generated by Visual Basic NET will be loaded as an additional form into the current project It will always have the Same appearance shown here to the r
133. e given week This program is always based on the one demonstrated in class but is a little more difficult and contains usually one extra skill Some weeks there may be a second exercise for you to do as well it depends on how complex the tasks you ve been asked to do are It is important that you complete each of these programs because your skills will build up week by week and if you miss out on either a class or writing a program or both then you may not have the skills you need to complete the next class program successfully Use the table in Appendix 3 Log of Completed Exercises to keep track on your own progress and make sure you get your work signed off by your lecturer Every week we will introduce a new object and you will have a document to complete called Object of the Week These documents will build up to create a comprehensive manual for you to refer to when you re writing programs independently so it is important that you complete each one and don t get behind Some weeks will include some homework questions for you to complete outside of class time These questions will help you to build on the practical skills and knowledge that you re gaining by completing the programs set on a weekly basis and again it is important that you complete them since they help you to develop your underpinning knowledge around the concepts of visual programming If you are set any homework questions the class will go through them w
134. e loop with the rest of the coding remaining exactly the same The same numbers will be used in the screenshots below notice the difference Do intTotal intFirstNumber intCounter 1 Loop While intTotal lt intSecondNumber a Do Loop While eel Do Loop While _o 2 j Number to add Number to add up to Number to add Number to add up to 5 5 5 3 Oom o Oom o The loop was The loop was performed 1 ti performed 6 times Lazy programming Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures Lecturer Jane Fletcher Do Until Loop Instead of specifying the condition as being the current situation i e while it still applies with the Do Until Loop iteration we specify the condition when we will stop i e the future condition If the condition applies already because the check is at the top of the loop if the condition already applies then the loop won t be performed at all like Do While Loop rather than Do Loop While Again we have used the coding from pages 75 76 and have substituted the code on pages 76 that appears in italics with the code below Notice that the condition has changed here from having the second number being less than the total to the total being greater than or equal to the second number D
135. e menu bar then Open Project Loading a project from Windows Explorer This is the personal favourite of the author of this document All you need to do is to open Windows Explorer and navigate to the folder holding your project Ils Exercise done in class prjWeekQneProgramDonelnClass Organize Share with Burn New folder f M 7 Fr Favorites Documents library e Foda ME Desktop prj WeekOneProgramDonelnClass i Downloads 5 Recent Places Name Date modified Type Size 04 07 2012 10 10 File folder 04 07 2012 09 40 Microsoft Visual 5 1 KE Libraries Documents RK safc You are looking for the file that is the Solution aspect of the project you have previously created In our example above it is the file that is circled Just double click on that file Visual Studio will open into the VB NET editor for you and load all aspects of your project If you already have Visual Studio open it will open another instance of it for you it will not overwrite any project that you already have open Do not panic if you can t see your form Visual Studio may open the project for you but it doesn t always open it in the same view that you closed it For example when we open the project created in the saving exercise m STaTE prjWeekOneProgramDonelnClass this 1S ppeemm neem the view we get of the project Where f S rene has my form gone po oeae i
136. e of a CheckBox beneath it When you reach the area of the form where you want to place the CheckBox press the left mouse button and drag across to the right ensuring you allow enough room for the associated label If you are putting the CheckBox inside a GroupBox then make sure that the GroupBox is active before clicking in the Toolbox to get the CheckBox In the illustraton alongside the form contains a GroupBox and has had three CheckBox objects added Their associated Text properties the labels alongside the check boxes have been changed to Bold Italics and Underline For this particular example font style may be bold or not italicised or not and underlined or not It might be that none of these items are selected or all of them or any combination of them In this way the CheckBox object differs from the RadioButton object where only one of a set of RadioButtons can be true Select font type Bald ttalics l Underine The default event for a CheckBox is the CheckedChanged event This is activated when the Status of the CheckBox is altered going from either ticked checked to not ticked no check in the box or vice versa However there are many more other events associated with the CheckBox control which can be explored by ensuring that the CheckBox is selected in the Objects ListBox and pulling down the list in the Events ListBox in the Source Code Editor view as shown below WindowsAp
137. e the contents of the list box For Each striItem In lstRhymes Items This piece of code takes each item that is stored in the Items list within the listbox object e Graphics DrawString strItem _ MyFont Brushes Black intTitleX intY Put the title on the page intY intY intFontHeight Next End Sub The code in bold is the code required to take each item from the ListBox object s Items collection and print it Now create a program to print from the list box in Exercise 15 1 Fe 9 Jane Fletcher South Nottingham College jes_ _ ___ SS a5 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 1 Unit Specification Lecturer Jane Fletcher Level 3 BTEC National Credit value 10 Guided learning hours 60 e Aim and purpose This unit aims to enable learners to develop the skills and understanding required to design and develop event driven applications e Unit introduction Event driven programming is a very flexible way of allowing programs to respond to many inputs or events Unlike traditional programming where the control flow is determined by the program structure the control flow of event driven programs is largely driven by external events Typically event loops are pre programmed to continually look for information to process This unit allows learners to become familiar with the
138. e versa Font Determines the size style and type of font to be used in the Text property of the CheckBox Its default value is to take the Font property of the GroupBox in which it sits Clicking on the ellipses to the right of the Font property in the Properties Window for the CheckBox generates the Font Dialog Box which allows the developer to select his or her choice of font style size ForeColor The colour of the text within the CheckBox s associated label Unless you change this property the label will have the default foreground colour similar to its owning GroupBox object Size Again an x y figure where x is the width of the object and y is the height of the object The unit of measurement is the pixel TabIndex Unless the label is to receive control during run time then the programmer can manually alter the Tablndex to be a high number using the Properties Window at design time Text The writing that appears in the CheckBox s label Normally it will start out with the default name of the CheckBox TextAlign Where the text will appear in the CheckBox s label The default value is MiddleLeft but each of the choices available to the Label object is available here Visible Set to either True or False determines whether the CheckBox and its associated label are visible or not Can be changed at either design time or run time C O ee Jane Fletcher South Nottingham College S lt Unit 14 E
139. easons why you must always internally document a program 9 We haven t discussed this in class yet but think about things that the user could do wrong when asked to enter information into a text box and list as many problems that you can think of that a programmer could consider when writing reliable and non crashworthy code 10 You have to write a program that has four buttons side by side each performing a similar task You have to make sure that the user can t use these buttons before certain criteria have been fulfilled Without going through and changing the properties of each button in turn in the code what can you do to make just one line of code stop each of the four buttons from working a er TTTTTT CC LQ 46 Jane Fletcher South Nottingham College p SS Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Revision questions Exercise 3 Lecturer Jane Fletcher 1 What is the prefix for a radio button 2 How do you ensure that a group of radio buttons work together as a team 3 What is the default event for a radio button 4 What is the essential logical difference between a radio button and a check box 5 What type of variable do you need to declare in a program if it is to hold whole numbers only 6 Declare one if the variables mentioned in
140. ecuting either in testing or during full implementation with the user The section of the program editor that allows the user to navigate between different Solution Explorer views of the program design code and between all forms used in the open program Goge The electronic area that has been ring fenced by the program to be used to store data 6 and to allow the program to execute correctly Subroutine A self contained section of program code Suntan The acceptable way that program code should be written Errors in syntax will stop a r program compiling and therefore running correctly Sustem For the purpose of this module a system is a collection of programs that go towards y performing a specific function An example system is a payroll system Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Quick start to terminology used in this unit f Lecturer Jane Fletcher Written document online or paper based aimed at fellow IT professionals giving Technical documentation necessary details about the current system program to enable maintenance to take place effectively The stage of the software design life cycle that involves the programmer putting Testing correct and incorrect data into the program and ensuring that a correct outcome ensues Toolbox The section of
141. ed 100 Below is a screenshot of a completely blank splash screen It has had all its objects removed including the panel It is now a blank canvas and you can put whatever image s labels ProgressBars etc that you think is appropriate to your project SENN R SplashScreenl vb Design Xx Fite SA ET One object that you MUST include however is a Timer this is P what will keep your splash screen active and will load the first real screen of your project 81 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Making a project look more professional Lecturer Jane Fletcher The first thing you are going to have to do is to ensure that the splash screen is the first screen within the project to load the default loading screen is always Form1 so this must be altered To do this click on Project on the menu bar and then the last item in the list which is always the project s name followed by the word Properties wo wiromo MisGi Vel So TSO File Edit View Project Build Debug Team Data Format Tools Test i ala gi E F P In the screenshot here the project hasn t been saved yet so is RRM succor e 7 s 9 Ii Tooli tt Add Component called WindowsApplication1 The last item in the list of
142. ed diagrams and or structured English to show step by step how the logic of each part of the system will work The developer then has a structured walk through of the structured designs with the systems analyst to get the seal of approval before carrying on to the programming software building stage How do write structured English e Structured English uses a subset of the English language that we write every day It uses e Verbs doing words and e Nouns naming words e It does NOT use e Adjectives describing name words or e Adverbs describing doing words e It should read like ordinary English e It should have appropriate indentation Tips for writing clear structured English e There are no set standards for structured English e However keep your language tight don t use description for example e Write in blocks and use good indentation to make it easy to identify what code belongs to which process e Keep to the sequence in which events happen e Identify choices selections Ifs and Select Case iterations loops for how many times you will do something O A ae 89 Jane Fletcher South Nottingham College y aaee a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Writing structured English e Verbs to use when writin
143. ege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to illustrate how to make the TabControl object work without actually clicking on the tabs themselves It is the follow up program to the one on the previous pages 1 When the program loads the entire form should be visible 2 Throughout the program use the font of your choice 3 The Close button should close the program 4 The TabControl should be renamed to tbMenu 5 In the TabPages property of tbMenu five tabs should be declared and named as follows First page tblintro Second tbChoice1 Third tbChoice2 Fourth tbChoice3 Fifth tbChoice4 PAN TD 6 The TabControl should then be drawn using the following code in the Drawltem process of that object This subroutine is called every time the tabs are accessed Firstly we ll define some parameters These are used to draw the tabs Tabs aren t objects like we know them they are drawn fresh each time we use them Dim CurrentTab As TabPage tbMenu TabPages e Index Dim ItemRect As Rectangle tbMenu GetTabRect e Index Dim FillBrush As New SolidBrush Color Black Dim TextBrush As New SolidBrush Color White Dim sf As New StringFormat sf Alignment StringAlignme
144. el Ga EL ee E ee E u CECE EEE Debug this case the developer hovers over the debugging icon in the icon bar How long it lwb Design x Start Debugging F5 suan re takes to get onto the screen once the mouse is in position and how long it remains on the screen whilst the user remains in position is determined by the developer within code The first thing to do when establishing a ToolTip is to declare it This is not essential if you have placed a ToolTip object on the form in design mode Set up the tooltips Dim toolTip1 As New ToolTip The coding above declares the ToolTip object It is done within the Form_Load event which you reach by double clicking on the Form object from the Form editor The coding below also occurs within the Form_Load procedure and sets up timings that apply to the ToolTip object There are three aspects to the timing reading in order down the code below how long you have it on screen AutoPopDelay the delay before the ToolTip text appears InitialDelay and the delay before you reshow the ToolTip ReshowDelay Timings are based on 1000 being equal to one second Set up the delays for the ToolTip toolTip1 AutoPopDelay 5000 toolTip1 InitialDelay 1000 toolTip1 ReshowDelay 500 The ToolTip will not appear automatically so that needs to be coded too in the Form_Load event Force the ToolTip text to be displayed whether or not the form is
145. elected the Drawltem method as shown in the Private Sub routine title Private Sub tbMenu_DrawItem ByVal sender As Object ByVal e As _ System Windows Forms DrawiltemEventArgs Handles tbMenu DrawItem This subroutine is called every time the tabs are accessed Firstly we ll define some parameters These are used to draw the tabs Tabs aren t objects like we know them they are drawn fresh each time we use them Dim CurrentTab As TabPage tbMenu TabPages e Index Dim ItemRect As Rectangle tbMenu GetTabRect e Index Dim FillBrush As New SolidBrush Color Black Dim TextBrush As New SolidBrush Color wWhite Dim sf As New StringFormat sf Alignment StringAlignment Center sf LineAlignment StringAlignment Center If we are currently painting the Selected TabItem we ll change the brush colors and inflate the rectangle If CBool e State And DrawitemState Selected Then FillBrush Color Color wWhite TextBrush Color Color Black ItemRect Inflate 2 2 End If Next we ll paint the TabItem with our Fill Brush e Graphics FillRectangle FillBrush ItemRect Now draw the text e Graphics DrawString CurrentTab Text e Font TextBrush _ RectangleF op Implicit ItemRect sf U A 38 Jane Fletcher South Nottingham College amna Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commo
146. en Notice that the location comectioteamrcjt Open File has changed to the path that you selected above but is still only at iu Weekly programs and not Week 01 ioe Close Project ia Save Form1 vb Ctrl S Save Project X Name WindowsApplication1 Location C Users Jane Documents Unit 14 Event Driven Programming Weekly Programs v Solution Name WindowsApplication1 4 Create directory for solution C j C k on t h e 66 B rowse b u tto n Add to source control to go further down the Weekly Programs path o0 Project Location ees JQ Unit 14 Event Driven P Weekly Prog s l 2 The Project Location dialog box appears e e From here you can click on Week 01 and o0 Microsoft Visual St Name ate modifie ype R Sica wee corms wee then click Select Folder Notice that Week He Favorites 01 has been added to the Location text box moe If you have Exercise done in class as a folder Downloads Hl Recent Place open that one too a Libraries Documents The project name is shown in the first text box a Music A ea E Pictures the default name is WindowsApplication1 oo z This is NOT a good project name because when Folder TT MePa paa Cance Se 4 Driven Programming Weekly Programs Week 01 X Browse you re on week 30 of this course you will haye rcs eine upwards of 60 of these s
147. en Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer e Graphics DrawString MyFont Brushes Black intX intY Blank line intY intY intFontHeight Ji oy hor el P 7 it Lecturer Jane Fletcher e Graphics DrawString For you amp strName amp _ we have written this special piece of prose _ MyHeaderFont Brushes Black intX intY Put the title on the page intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer e Graphics DrawString MyFont Brushes Black intX intY Blank line intY intY intFontHeight e Graphics DrawString Mary had a little lamb _ MyFont Brushes Black intTitleX intY Put the title on the page intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer e Graphics DrawString Whose fleece was white as snow MyFont Brushes Black _ intTitlex intY Next line intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer e Graphics DrawString And everywhere that Mary went MyFont Brus
148. er documentation for many years and has seen all manner of wordage brought into play in user manuals some of which you would be embarrassed to repeat to your grandmother Remember that your users are your clients and you would like them to continue supporting you in your work this involves being polite to them Generally speaking users require simple easy to follow instructions that are easy to find when they are needed and aren t confusing or ambiguous They want to be able to pick up the software and the manual and start working without the need for many hours of practice and or training Make sure that the most often performed tasks in the software are documented thoroughly and that that documentation is easy to find These instructions could be on screen or paper based but the same rules apply Depending on your software you might have to provide a very thick comprehensive manual or just simple step by step instructions or a combination of the two Tips for writing user instructions e Prefix each section of the instruction with a clear title stating what these instructions are going to explain e Don t hide vital instructions on how to perform a frequently needed task inside a section explaining something else e Start your instructions with a verb a doing word like this list of tips for example e Use a numbered list if it is vital that you perform certain tasks in that given order e Define any tasks that
149. er program as long as the appropriate data type is used see section Data types Arithmetic operators The table below shows the arithmetic operators and also their order of precedence i Visual Basic symbol Order of precedence a ee ee S Integer division Exponentiation Logical operators There are several logical operators that you will use frequently during this unit These simple operators are detailed in the table below There are also some complex logical operators which are discussed below the table symbol Equalto fAsBThn More complex logical operators Logical operators compare Boolean expressions and return a Boolean result The And Or AndAlso OrElse and Xor operators are binary because they take two operands while the Not operator is unary because it takes a single operand Some of these operators can also perform bitwise logical operations on integral values And The And operator performs logical conjunction on two Boolean expressions If both expressions are True then And returns True If at least one of the expressions evaluates to False then And returns False If txtFirstNumber Text lt 10 And txtSecondNumber Text lt 10 Then lblOutcome Text Both inputs are less than 10 End If U ie 66 Jane Fletcher South Nottingham College aae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advan
150. ers entered Count of numbers entered 13 18 Average number entered N Co RON lt ro s 3 NewToolStripmenultem 3 Tabel 4 CloseToolstripenultem 6 TextBox1 txtNumber Label7 lblHighest Button1 btnClickMe Label8 blTotal GroupBox2 1800 Label9 lblCount lblCount ta ListBox1 lstNumbers Label10 ree 155 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 7 Number processing with variables Lecturer Jane Fletcher A program is needed to meet the following requirements 1 The menu strip should have one item at the top level File 2 File should contain two items New and Exit 3 Exit should close the program 4 New should reset the form to its original condition and all variables should be set to their original values 5 When the program loads everything should be visible on the form 6 The program needs these variables five integers intNumber intCount intTotal intHighest and intLowest and a decimal decAverage These should all be declared at the top of the program 7 The value 0 should be stored in intHighest 8 The value 10 000 should be stored in intLowest 9 The cursor should be set into the text box 10 The user s entry should be validated a
151. essed will always be at the top prjWeekOneProgramDonelnClass in our example here Start Page Microsoft Visual Studio lolle ss File Edit View Debug Team Data Tools Test Window Help Deg a d sadlala2 9 8 Gl gt vases Eren PER Toolbox adi Start Page X Solution Explorer ax 4 General gt There are no usable controls in of ager this group Drag an item onto Visual Studio 2010 Professional this text to add it to the toolbox PS Get Started Guidance and Resources Latest News L Connect To Team Foundation Server ro New Project Fj Open Project What s New in Visual Studio 2010 Learn about the new features included in this release Welcome Windows Web Cloud Office SharePoint Data Visual Studio 2010 Overview What s New in NET Framework 4 What s New in Visual Basic Customize the Visual Studio Start Page Recent Projec eye prj VeekOneProgramDonelnClass aa prjPrintingFromAListBox Double click on the solution file prjWeekOneProgramDonelnClass Your project will now open If you can t see your form follow the procedure described on page 61 Using Open Project on the Start Page Open Visual Studio NET and on the Start page click on Open Project 0 Start Page Microsoft Visual Studio co e ss File Edit View Debug Team Data Tools Test Window Help Pae SG ad naw 4 aiAlalSe2 9 C 2 O gt w aes Enimie 3 gS Toolbox eai Start Page X Solution Explorer qx 4
152. etcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Lecturer Jane Fletcher A program is needed to meet the following requirements When the program loads the entire form should be visible and the cursor placed in txtForename gbDays should be disabled When the user clicks btnProcess the program should validate the entry in txtForename as s having a length between 1 and 12 characters The same validation applies to txtSurname Any illegal input should generate a message box displaying a suitable message the text within the text box should be deleted and the cursor placed into the text box ready for user input Once the number has been validated gbDays should be enabled and If the user checks chkMonday the program should display a concatenated message in the format of into lstHistory Forename Surname works on Monday Do the same for each of the check boxes amending the day as appropriate When the user clicks btnDeleteSelected the program must make sure that the user has actually selected something in lstHistory If they have then that entry should be deleted When the user clicks btnDeleteAll the program must ask the user if they are sure that they wish to delete the entire contents of the list box via a message box If the user an
153. eturn menu item on Form2 should dispose of Form2 and return control back to Form1 OE O eee 95 Jane Fletcher South Nottingham College S Unit 14 Event Driven Programming edexce l SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 12 Creating a Login system Lecturer Jane Fletcher Coding for this program FORM1 Public Class Form1 Dim intUser As Integer Dim strPassword As String Private Sub Form1_Load ByVal sender As System Object ByVal e As System EventArgs _ Handles MyBase Load Set the defaults of the form Me Height 151 MenuStrip1 BackColor Color White End Sub Private Sub btnUser1 Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnUser1 Click btnUser2 Click _ btnUser3 Click btnUser4 Click btnUserS5 Click btnUser6 Click Get the identification of the user logging into the system intUser sender text strPassword Blank out previous input to the password Me Height 294 End Sub Private Sub btnPass1 Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnPass1 Click btnPass2 Click btnPass3 Click btnPass4 Click btnPass5 Click btnPass6 Click Concatenate the text on the clicked button with previous clicks to form the passcode of the user strPassword strPassword amp sender text lblPassCode Text strPassword End Sub P
154. f the form Me Height 248 Tell the program that it is the first number that the user is picking bFirst True Sub Private Sub btn9 Click ByVal sender As System Object ByVal e As System EventArgs _ End Handles btn9 Click btn8 Click btn7 Click btn6 Click btn5 Click _ btn4 Click btn3 Click btn2 Click btn1 Click if bFirst is true then it means that we re in the position of picking out the first number sender is the word for the actual button that the user clicks Since we re doing the same processing for all the buttons we don t need to write a separate event for each of them The same code does for all The only difference in processing is whether we re on the first number or the second one If bFirst Then intFirst sender text bFirst False Else intSecond sender text End If Alter the size of the form Me Height 391 gbNumbers Enabled False Sub Private Sub btnPlus Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnPlus Click btnMinus Click btnMultiply Click btnDivide Click 148 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips Save the operator that the user wants to use and then disable all operators but equals strOperator sender text gbN
155. for the Label object is TopLeft but to change it click on the box representing the position where you want the text to appear The selected position has a flat appearance in the TextAlign box as shown above Visible This property can be set to equal True or False both at design time and within code The developer may wish to have a label hidden until certain conditions are met in which case the Visible property is more appropriate than the Enabled property aay 0 t lt i COSOSC 8 Jane Fletcher South Nottingham College jE LLLE Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls GroupBox control Lecturer Jane Fletcher GroupBox The GroupBox control as its name suggests is used to group together other controls that need to either work together as a team such as radio buttons or for visual effect i e controls that are to work together to perform a specific purpose to either look good or to show the user that these controls are part of the same groups of input or output SANS Notifylcon NumericUpDown The GroupBox control can be found in the Toolbox under the Containers menu In order to get a GroupBox onto your form select the GroupBox object in the Toolbox by clicking on it and move across to the form When you get the location on the form whe
156. further folder and call it Exercise done in class This is the folder where we will be putting our first program a Ca Unit 14 Event Driven Programming Weekly Programs Week l gt F Organize Open Share with E mail Burn New folder zz i Fr Favorites Documents library E rode EE Desktop Week 01 x i Download E Name Date modified Type Size Recent Places Ji Exercise dene in class 03 07 2012 10 54 File folder Ca Libraries Documents LE My Documents _ E E ai mi T Your folder structure should look similar to the one shown in the illustration above You are now ready to start developing your first project O t eS 53 Jane Fletcher South Nottingham College ymae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Starting a new project Lecturer Jane Fletcher The first thing you are going to have to do is to load the Visual Studio NET software Depending on the setup of your computer you will find it on the following path Start gt All Programs gt Microsoft Visual Studio 2010 gt Microsoft Visual Studio 2010 The icon for the Visual Studio software looks like the illustration to the right and this is the one that you oO Microsoft Visual Studio 2010 must click in order to get Visual Studio to load You may find th
157. g an overflow The value must be numeric The value must be in the range specified In this instance the numbers allowed are in the range of 1 to 100 Anything outside that range is invalid Remember to internally document your code OS lt i _OONSS S a 33 Jane Fletcher South Nottingham College S Lecturer Jane Fletcher Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Lecturer Jane Fletcher 5 0 Specification for program developed in class First check boxes Enter name 2 Forename Jane Surname Fletcher mm Pick days worked Ea W Monday Tuesday Wednesday 9 10 11 12 and 13 Thursday W Friday Employment history Jane Fletcher works on Monday Jane Fletcher works on Wednesday Delete Selected Jane Fletcher works on Friday 15 Delete All Enter another employee ltem Object CheckBox2 chkTuesday CheckBox3 chkWednesday CheckBox4 chkThursday CheckBox5 chkFriday GroupBox 15 ListBox1 lstHistory _ e TextBox2 txtSurname utton1 btnProcess roupBox2 gbDays CheckBox1 chkMonday La TextBox1 txtForename B G Button3 btnDeleteAll 18 Button4 btnEnterAnotherEmployee Button5 btnClose 15 Button2 btnDeleteSelected 134 Jane Fl
158. g structured English Lecturer Jane Fletcher Subtract Multiply Display Calculate e Writing nouns use i capping e It s legitimate to use variable names in structured English Writing iterative statements in structured English FOR condition Iterative statements NEXT Or DO WHILE condition Iterative statements ENDDO Or DO Iterative statements UNTIL condition Notice the indentation here the iterative statements between the looping clauses are indented from the looping clause and each looping clause start has to have an end looping clause which must line up Writing selection statements in structured English IF condition Imperative statements END IF Or a e a L L 90 Jane Fletcher South Nottingham College SSS Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Lecturer Jane Fletcher SELECT CASE tem CASE Item condition Statement s CASE Item condition Statement s CASE Item condition Statement s END SELECT Where does structured English fit in e Structured English is written AFTER the design of a program form designs form dictionaries data dictionaries but e BEFORE the program itself Why do it Do have to YES You have to do it e Because it helps you to determine logical order for your statements e Because it helps
159. gain input from the user 2 Name three objects that could be used to give output to the user 3 Is a label a good object to use to get input from the user Explain your answer 4 Name three ways that a number be validated when it is input to a program 5 Explain when you would use a radio button rather than a check box and give an example when a radio button is better Give an example where a check box would be better 6 Name the three control structures Think Wednesday s lesson 7 Name three types of variable that can be used in any program 8 Explain why you would use each of them rather than any other type of variable ee TTCCOCOCidsS 50 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Creating a folder structure edexcel advancing learning changing lives Lecturer Jane Fletcher This section will explain how to set up a folder structure to enable you to locate your projects easily Every project that you create MUST have its own folder If you are going to use a previously written project as the basis to develop a further project that has different features then you should copy the entire folder of the original project and paste it with a new name Before you start thinking about creating a new project you must first design a file system where you wil
160. gered Processes for a program should be defined in the program specification by the systems analyst A collection of code that performs a specific function An example program is the Program Calculator that comes in Accessories ee A document written by the systems analyst to tell the programmer exactly what a Program specification i program or suite of programs should look like and do The act of creating programs including the initial making of a form the coding Programming i associated with the form and the testing that ensues The section of the program editor that allows the programmer to set initial values to Properties Window i ae oat the properties of controls used within a form at design time A particular attribute that goes towards defining what a control looks like or acts like Each control has a number of properties Some properties can be defined altered at design time some at run time and some can be defined altered at both design and run time Property A reserved word is one that has an inbuilt meaning within the NET framework and cannot be used by the developer for any other purpose For example the words Private and Sub cannot be declared as variable names If you try you will get an error message Keyword is not valid as an identifier Reserved word Run The term used as a catch all and means compile the program and then make it work eee The time when the program is ex
161. gham College p So lt Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher 8 0 Specification for program developed in class Working with dates Monday 28 11 2011 SS 105 December 2011 bi ll EZ 05 12 2011 is 20 days to Christmas Item Object Item Object a Form 6 e MenuStrip1 File DateTimePicker1 dtpSelectedDate NewToolStripMenultem 8 GroupBox2 4 CloseToolStripMenultem sr Label2 lblMessage Labet btTodaysbate a eseseses seaesNONNNNNeeeS 161 Jane Fletcher South Nottingham College paea Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher A program is needed to meet the following requirements Overview 1 When the program loads the entire form should be visible 2 Throughout the program use the font of your choice 3 Use the background image of your choice for the form Set the BackgroundIlmageLayout of the form to be Stretch if appropriate to your image 4 The program needs these variables declared at the top of the program Dim dtToday As Date Date Today Dim dtSelectedDate As Date Di
162. ham College a mnm N Unit 14 Event Driven Programming edexce l SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 7 Number processing with variables pna Lecturer Jane Fletcher End If ProcessNumber Put the cursor back into the text box after clearing it txtNumber Text txtNumber Focus End Sub Private Sub ProcessNumber Process the number entered If intNumber gt intHighest Then It is so store it as the current highest number entered intHighest intNumber End If Now display all new values in the label lblHighest Text intHighest End Sub Private Sub NewToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles NewToolStripMenuItem Click Clear everything down and set back to original values intHighest txtNumber Text txtNumber Focus End Sub End Class ee See 58 Jane Fletcher South Nottingham College ymae 0 a Unit 14 Event Driven Programming SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Example programs 7 Number processing with variables edexcel advancing learning changing lives Exercise 7 1 Click me Analysis Lowest number entered Highest number entered History i om Sr Total of numbers entered Count of numbers entered Aver
163. ham College fe__ ____ eS aaa _ Mu Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Lecturer Jane Fletcher intQuantity now contains the value of how many of that title have been ordered already c The program must now remove the old value of how many have been ordered from the Ordered list Remove the old amount of blu rays lstOrdered Items RemoveAt 1lstTitle SelectedIndex d The user wants to add one to the order for that particular title so we must account for that Add one to how many we ve ordered intQuantity 1 e We now update the quantity in the Ordered list box by inserting the new quantity ordered in at the appropriate place place stored in intPointer quantity in intQuantity Insert the updated number of blu rays lstOrdered Items Insert intPointer intQuantity 11 On the click event of lstRemove a For this process we must ascertain upon which title the user wishes to decrease the order Work out which blu ray has been selected Dim intPointer As Integer intPointer lstRemove SelectedIndex intPointer now contains the value of where we are at for each of the list boxes in the program b After that the program must query how many of that particular title have already been ordered by looking at
164. hanged event which occurs once the user has actively altered the selected date on at run time There are other events available which can be explored in the Source Code view of the Editor by clicking on the DateTimePicker object s name in the left hand ComboBox and opening up the list of available events in the right hand ComboBox as below Formi vb X aouu An Neah olution rer enma D Bieoactorations gt J e Do n Miu eee f E There are no usable controls in this group Drag an item onto this text to add it to the toolbox End Class O a 33 Jane Fletcher South Nottingham College y aaee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls DateTimePicker control Lecturer Jane Fletcher Commonly used properties of the DateTimePicker control CalendarFont The font in which the rolled down calendar will be displayed at run time This property does not change the font in the ComboBox aspect of the control CalendarForeColor The colour of the date numbers on the rolled down calendar at run time CalendarMonthBackground The background colour of the rolled down calendar at run time CalendarTitleBackColor The background colour of the banner containing the month name in the rolled down calendar at run time CalendarTitleForeColor The colour of the text containing the
165. hat an enabled Timer_Tick event works is that it is triggered each time the Interval is reached If the Interval property of the Timer is set to 1000 then the Tick event will occur every second and whatever code occurs within that Tick event will be executed every second Bear in mind that this could easily cause endless loops and tie up your computer s processing memory It is important to remember that unless you want your Tick event to run constantly if for example you have a clock running on your form that you want to update every second that you disable the timer at the appropriate point It is possible to alter the Enabled property at run time or design time or a combination of the two A Timer s Tick event can be active throughout the running of a program the Timer itself doesn t have to be accessed at all to cause it to trigger the Tick event unless it is to either start the Tick event procedure or to stop it It is happy to run in the background without intervention but it can make debugging a program step by step very difficult O lt lt lt i lt i lt i lt i lt i lt i isSOCS ee 41 Jane Fletcher South Nottingham College a mnm Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Timer control Lecturer Jane Fletcher Commonly used Properties of the TabContr
166. her txtSurname welcome to programming Note 1 Error occurred during test number 8 instead of the program displaying Jane Fletcher welcome to programming it displays JaneFletcher welcome to programming The coding before correction is Concatenate the content of the text box with a message and display it to the user lbl1Message Text txtForename Text amp txtSurname Text amp welcome to programming The correction required is to alter the concatenation to include an extra space as shown below Concatenate the content of the text box with a message and display it to the user lblMessage Text txtForename Text amp amp txtSurname Text amp welcome to programming The repeated test now indicates that this error has been removed Component s tested Expected result Actual result number btnDisplay_Click Jane and lblMessage displays txtForename and Fletcher Jane Fletcher txtSurname welcome to programming Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs Lecturer Jane Fletcher This section will provide you with the specifications for and coding of the programs that will be developed in class It will also provide you with the specifications for some extension programs that you will be re
167. hes Black _ intTitlex intY Next line intY intY intFontHeight e Graphics DrawString That lamb was sure to go MyFont Brushes Black _ intTitlex intY Next line intY intY intFontHeight intY intY intFontHeight e Graphics DrawString T HE END _ MyTitleFont Brushes Black intTitleX intY Put the title on the page Output from this program will read Print preview 42 00 B chs FoETAY CORN ER For you Jane we hare written this special piece of prose Mary had a little lamb Whose fleece was white as snow 4nd everywhere that Mary went That lamb was sure to goa T H E E MNM D L Jane Fletcher South Nottingham College pae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing Lecturer Jane Fletcher Coding for this program Public Class Form1 Dim strName As String Private Sub Form1_Load sender As System Object e As System EventArgs Handles MyBase Load Set the defaults for the project MenuStrip1 BackColor Color White End Sub Private Sub CloseToolStripMenuItem Click sender As System Object e As System EventArgs _ Handles CloseToolStripMenuItem Click Me Dispose End End Sub Private Sub PreviewToolStripMenuItem Click sender As System Object e As System EventArgs _ Handles PreviewToolStripMenuItem
168. ho would want to try the result The way to get a RadioButton onto a form is to first of all place a GroupBox control for them to sit in After that make sure that the GroupBox is the active control i e there are visible grab handles around its edges as in the first illustration below and then click on the RadioButton icon in the Toolbox second illustration Move across to the GroupBox and then press the left mouse button when you reach the location of where you want the RadioButton to sit third illustration Naming convention gives RadioButtons a prefix of rad Toolbox Zal Select drink flavour ProgressBar Cee ace eran ere RadioButton RadioButton a5 ORichTextBox p b TextBox Ra ToolTip a gt TreeView no a seeeereeeeeceereeereneereerena 0 em RadioButtons have their own associated label Text property used to display the nature of this choice to the user In the example below the first illustration the default value in the Text property is the name of the object which in the case of RadioButtons is RadioButton1 RadioButton2 and so on The second shows the Text property having been changed to Orange and the third shows the result on the RadioButton itself a A RadioButton1 System Windows Forms z aA F a 5 Select drink flavour TabIndex 0 2 TabIndex 0 a Orange TabStop True TabStop True Tag Tag Text RadioButton1 Text Orange TextAlign MiddleLeft TextAlign MiddleLeft TextimageRelati O
169. hould be stored in dtSelectedDate 15 The difference between the selected date and Christmas of the current year should be determined by using a DateDiff operation in the following format intDaysDifference DateDiff DateInterval Day dtSelectedDate dtChristmas where intDaysDifference is declared as a local integer This operation takes the Day interval as its required result and works out the difference between the two dates 16 Display the days to Christmas from the selected date in lblMessage in the format dtSelectedDate is intDaysDifference to Christmas eae 62 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher Coding for this program Public Class Form1 Dim dtToday As Date Date Today Dim dtSelectedDate As Date Dim intYear As Integer dtToday Year Dim dtChristmas As Date New Date intYear 12 25 Dim intDay As Integer Dim strDay As String Private Sub CloseToolStripMenuItem Click sender As System Object e As System EventArgs _ Handles CloseToolStripMenuItem Click End the project End End Sub Private Sub Form1_Load sender As System Object e As System EventArgs Handles MyBase Load Set the defaults for the form MenuStrip1 ForeColor Color Black MenuStrip1 BackColor
170. ht 248 Change the height of the form bFirst True We re starting again from scratch gbNumbers Enabled True So that the user can start picking out numbers again Enable all the operator buttons and disable equals btnDivide Enabled True btnPlus Enabled True btnMultiply Enabled True btnMinus Enabled True btnEquals Enabled False End Sub End Class pC 14 9 Jane Fletcher South Nottingham College paee a lt 6 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips Lecturer Jane Fletcher Exercise 6 1 Processing Numbers Processing Numbers 11 2 Fie File Help ii number to process The purpose of this program is to enter two En numbers each of which must be within the range Step 2 Select Operator of 1 to 100 then to select an operator to use on pa a wa these numbers Once you ve clicked on an operator the answer will be displayed Step 3 Display Answer 10 46 460 00 Go to File and Hew to continue Return CloseToolStripMenultem HelpToolStripMenultem Label3 lblAnswer extBox1 txtNumber1 OT O A 150 Jane Fletcher South Nottingham College pame N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing le
171. i CRR OC U YCOCOC C CR Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development lt Lecturer Jane Fletcher Acknowledgements To all BTEC National students past present and future each of whom has helped to teach me how to program Without them would still be an over paid Software Consultant with dubious skills some of which pertained to programming am grateful for your patience while learned how to teach you to program and for your guidance when things went wrong and your humour while stood at the front of the class looking bemused confused and ever so slightly embarrassed You have all rocked programming SF _eeststi i _ Cai COS r Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development EG Lecturer Jane Fletcher S ti i lt i CRR OC U YCOCOC C CR Jane Fletcher South Nottingham College jE LLL Event Driven Programming Using VB NET edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Contents Topic Page Introduction to the course 1 Quick start to terminology used in this unit 2 Visual Stu
172. ighest ElseIf txtFirstNumber Text lt txtSecondNumber Text Then This means that the first number entered less than the second number lblOutcome Text First number entered less than the second number ElseIf txtFirstNumber Text txtSecondNumber Text Then The contents of both text boxes are the same lblOutcome Text Both numbers are equal in value End If Select Case End Select The Select Case End Select statement is another way of testing either the contents of a variable or of an object such as a text box It can be used when you wish to test for different ranges as in Example 1 below or when you have a String text variable to examine as in Example 2 The Select Case part of the statement the first line determines which variable s content will be examined and the individual Case Statements following that are the ranges or instances to check for Once a match has been achieved the rest of the Case statements are ignored and control passes to the Statement following End Select ee eee Jane Fletcher South Nottingham College oD SS a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures J Lecturer Jane Fletcher It is possible to have a Case Else if you want to have a catch all clause should none of the Case checks
173. ight There is lots of code attached to the template shown below You won t want this so you can safely delete all except the top line and the bottom line Public NotInheritable Class SplashScreen1 and End Class SplashScreenl vb Design X PAJU NOE SplashScreenl vb X EIEN ean el ote Public NotInheritable Class SplashScreen1 TODO This form can easily be set as the splash screen for the application by going to the Application tab i h l Tomin 0 1 00 of the Project Designer Properties under the Project menu Hf it z i Copyright Private Sub SplashScreen1_Load ByVal sender As Object ByVal e is System ntArgs Handles Me Load it Set up the dialog text at runtime according to the application s ass ates information HF TODO Customize the application s comer tl information in the Application pane of the project prope peice aise tae ae bie nu SplashScreenl vb Design Form1 vb Design Application title S d b f If My Application Info Title lt gt Then Cary CO e e ore applica Public NotInheritable Class SplashScreen ApplicationTitle Text My Application Info Title Else If the application title is missing ApplicationTitle Text Sys sa em I0 Path pale aie ameWi End Class Scary code End If Format the version information using the text set into the Version control at design time as the deleted Torsattin ng s stri ing This allows Tor effective Jot aliz ation ifd r
174. im decNumber As Decimal the holder of the number Dim intNumberOfDecimalPlaces As Integer Private Sub btnEnd Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnEnd Click Stop the project Me Close End Sub Private Sub btnClear_ Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnClear Click Clear out the rubbish lstOutput Items Clear txtNumber Text txtNumber Focus End Sub Private Sub btnProcess Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnProcess Click Take the value entered in the text box validate it and display it in different ways If txtNumber Text Length Then MsgBox You must enter something for number MsgBoxStyle Critical _ No entry made for number txtNumber Focus Exit Sub End If If txtNumber Text Length gt 10 Then MsgBox You have entered too much information in number MsgBoxStyle Critical _ Too long an entry for number txtNumber Text txtNumber Focus Exit Sub End If If Not IsNumeric Val txtNumber Text Then MsgBox You must enter a number MsgBoxStyle Critical Not numeric txtNumber Text txtNumber Focus Exit Sub End If decNumber Val txtNumber Text If txtDecimalPlaces Text Length Then MsgBox You must enter something MsgBoxStyle Critical _ No entry made for number of decimal places txtDecimalPlaces Focus Exit Sub End If Yee 9 J
175. ing learning changing lives Example programs 11 Creating Web Browsers n Determine the first four characters in the variable strAddress to ensure that the user has entered www StrFrontBit Mid strAddress 1 4 o Look at the contents of strFrontBit If it is NOT equal to www then concatenate www onto the front of strAddress If strFrontBit www Then Else strAddress www amp strAddress End If p Navigate to the webpage indicated in strAddress woWebBrowser Navigate strAddress eee 86 Jane Fletcher South Nottingham College 2_ _ Sa ee SS 5 a Lecturer Jane Fletcher Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 11 Creating Web Browsers Lecturer Jane Fletcher Code for this program Public Class Form1 Private Sub btnGo Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnGo Click This button will check that the user has entered something and then will navigate to the web address Dim strAddress As String If txtAddress Text Length Then Exit Sub End If strAddress txtAddress Text strAddress LCase strAddress Dim strFrontBit As String strFrontBit Mid strAddress 1 4 If strFrontBit www Then Else strAddress End If www amp strAddress wbWebBrowser Navigate
176. ing lives User documentation Lecturer Jane Fletcher You will be shown an error message Look at the top line of this error message it says Input in first number is too long in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwooO You entered something into First Number that is not numeric Type your own first name into the box alongside the prompt First Number and click the Process button Input in first number isn t numeric Wal Xx You must enter a number in the range of 1 to 9999 You will be shown an error message Look at the top line of this error message it says Input in first number isn t numeric in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwooO You enter a number that is out of the accepted range of 1 to 9 999 Type O into the box alongside the prompt First Number and click the Process button Input in first number is out of range Ea Xx You must enter a number in the range of 1 to 9999 You will be shown an error message Look at the top line of this error message it says Input in first number out of range in the top line of this message and
177. ing the TextAlign property in the UseCompatibleTextRenderir Properties Window The default value is S tnement MiddleCentre but to change it click on ee the box representing the position where visible you want the text to appear The selected position has a flat appearance in the TextAlign box as shown above Visible This property can be set to equal True or False both at design time and within code The developer may wish to have a button hidden until certain conditions are met in which case the Visible property is more appropriate than the Enabled property er sseses se i lsSSSSN 14 Jane Fletcher South Nottingham College lh Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Label control Lecturer Jane Fletcher Label BI Al widows For The Label control is accessed from the Common Controls section of the Rg common controis Toolbox by clicking on the icon shown here The Common Controls are f ins listed in alphabetical order CheckBox ad CheckedListBox Combobox Labels are used either as prompts or to display information to the user They do not allow user entry at all The default event of a Label object is the Click event but as a general rule labels are not used for anything other than displaying information It isn t normal for
178. into the text box 10 The user s entry should be validated as being numeric and in the range of 1 to 9999 Any invalid entry should be reported to the user via a message box invalid input should be removed and the cursor set into the text box ready for further user entry 11 Valid user entry should be stored in the variable intNumber 12 Each number that is entered by the user should be processed as follows a If the value in intNumber is less than the value in intlowest then store the value of intNumber into the variable intLowest and display this number in lblLowest b If the value in intNumber is greater than the value in intHighest then store the value of intNumber into the variable intHighest and display this number in lblHighest c intTotal should be added to the value in variable intTotal and that value displayed in the label lblTotal d One should be added to the variable intCount e decAverage should be calculated by dividing intTotal by intCount and this value stored in decAverage f If the number entered is odd then one should be added to the variable intOdds and that value stored in blOdds 9 If the number entered is even then one should be added to the variable intEvens and that value stored in lblEvens 13 The text box txtNumber should be cleared and the cursor replaced there to wait for user input after this processing has occurred OH i O O C i SCS 60 Jane Fletcher South Nottin
179. inu Above you can see the Form Editor or Design View of VB NET If you turn to page 6 of this document you will see a breakdown of what each aspect of this screen does To the left you will see the Toolbox be WindowsApplication1 Mi sual Stuc File Edit View Project Build Debug Team Data Tools Tes iala El Code F7 If you do NOT see the Toolbox click on View in the menu bar and py 3 omen site E then select Toolbox This is shown to the right You can also click 2 et mee sa2inos e eq gills Ga Th Team Explorer Ctrl CtrleM Ctrl Alt X together and it will do the same thing give you your H seee omes toolbox back 23 ert cute Ci Toolbox Ctrl Alt X File Edit View Project Build Debug Notice on the Toolbox that there is a cee ee Aag J el al 4 4 4 picture of a drawing pin on the top me e W Toolbox line in the illustration below it is Property Pages Shift F4 S i All Windows Forms fa pointing downwards This drawing A 4 Common Controls pin holds the Toolbox in File Edit View Project Build Debug Team Data OR Pointer place If you click on it the 4G 4 da 6 5 4 aa 5 o n lt Toolbox will hide on the left PISH E E All Windows Forms f hand side of the screen and will only be visible when you hover ff common Controis 7 over the Toolbox tab to the left of the screen The drawing Ey k Pointer pin lies on its side during this view To get the Toolbox back zi sou
180. ion a COSY lt lt lt lt 3 Jane Fletcher South Nottingham College a mnm __ mu nu Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures Dim intNumberOfIterations As Integer The variable to hold how many iterations the user wants Lecturer Jane Fletcher Store the value within txtInput in intNumberOfiIterations intNumberOfIterations txtInput Text Store the value within txtMiltiplier in intMultiplier intMultiplier txtMultiplier Text Using intCounter as a well counter loop through the coding within the For and Next statements incrementing intCounter starting at 1 by 1 until intCounter reaches the value stored in intNumberOfiIterations For intCounter 1 To intNumberOfIterations Store the value of multiplying the counter with the multiplier intAnswer intCounter intMultiplier Output the answer to the list box lstAnswer Items Add intCounter amp amp intMultiplier amp amp intAnswer Next The Listbox object IstAnswer when the user enters 10 into the number of iterations and 20 into the multiplier For Each Next If you have an object such as a ListBox or ComboBox or an array of items and want to process each one of them one after the other use For Each Next
181. items m a available from the Project menu is WindowsApplication1 at coo i ada nenten Cutest Properties Click on that Yt a aaan a2 G Datas Show All Files scores S 8B WindowsApplication1 Properties The Properties window for the project will open in the central pane of the editor ormon 7 N Compile WindowsApplicationl X JERN A SplashScreen1 vb Design Form1 vb Design Assembly name Root namespace z Make sure that the WindowsApplication lt i References Application tab is the Application type Icon Resources Windows Forms Application gt Default Icon 4 r active one by clicking on Startup form the appropriate tab a a Saal Assembly Information View Windows Settings Notice halfway down the form there is a_ ListBox underneath the label saying Startup form Click on the arrowhead to the right of the ListBox My Extensions vV Enable application framework Seoni Windows application framework properties V Enable XP visual styles Once you ve clicked on the arrowhead a list Of sicatio the forms available within the current project EAER will populate the Items property of that S sindovstston Verse ListBox In the example to the right you will secs 9 aes oo JE see that Form1 and SplashScreent are se smem available and that Form1 is selected as the current Startup form Click on Spl
182. ith your lecturer during the next lesson so you get the chance to put right any mistakes you might have made There are two assignments for this unit the first one is theoretical and you will be required to do lots of research in order to complete it The assignment must include a full bibliography created using the Harvard Referencing System and without it your work will be rejected The second assignment is a practical one and requires you to produce a program and all the associated documentation In order to complete this you must have done all of the programming exercises starting on page 111 of this book if you have you will be able to write the program with little difficulty since all the skills you need will have been already developed This unit is one you will either love or hate keep up with the work and you Il love it a F lt lt i lt i lt i a lt Or Jane Fletcher South Nottingham College J E LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Quick start to terminology used in this unit f Lecturer Jane Fletcher One of the most difficult things to get to grips with when you are new to programming is the different terminology that is used within a software development environment The easiest thing to do is to complete a glossary of terms like the one given in templa
183. iven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing Lecturer Jane Fletcher A program is required to meet the following requirements This program introduces the concept of printing within a NET environment The menu strip should have two items at the top level File and Print File should contain two items New and Close Close should close the program New should reset the form to its original condition and all variables should be set to their original values The Print option on the menu strip should be disabled 5 When the program loads everything should be visible on the form and the background colour of the menu strip set to whatever is used within the program for the background colour of the form The Print option on the menu strip should be disabled 6 The program needs this variable to be declared at the top of the program strName as string 7 At design time PrintDocument1 should be assigned as the Document in the PrintPreviewDialogue control 8 The processing for btnValidate should be as follows a The user s entry into txtName should be validated to be within the length of 1 to 20 characters Anything outside that range should be rejected with an appropriate error message The user should be exited from that procedure b Valid input should be stored in strName c The message
184. k at the top line of this error message it says No input in Second number in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwoO You entered something that is too long Now enter 11111111 into the box alongside the prompt Second Number and click the Process button Input in Second number is too long Es Xx You must enter a number in the range of 1 to 9999 You will be shown an error message Look at the top line of this error message it says Input in Second number is too long in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwooO You entered something into Second Number that is not numeric Type your own Second name into the box alongside the prompt Second Number and click the Process button Input in Second number isn t numeric 23 x You must enter a number in the range of 1 to 9999 ee Sf et _SOsOsOsOSsOsOOeSSee 104 Jane Fletcher South Nottingham College p auae 0 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives User documentation
185. k for the bathroom or to ask directions to the nearest hospital in Klingon but that s probably about the extent of it Well programming is a foreign language to people new to it the author is more fluent in Visual Basic NET than she is in English and so are the concepts of logic and simplicity Programming statements are extremely simple once you understand them but when you start out as a fledgling developer you tend to imagine that you should be thinking in a far more complex way than you really need to If you can write a simple Step by step list with each step being very small and not complex than you can program Trust me I m a programmer If can do it anybody can ce lt iL t TT C VSD 111 Jane Fletcher South Nottingham College p lt Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 1 Using Labels and Buttons p aa Lecturer Jane Fletcher 1 0 Specification for program developed in class First program Hello Display btnDisplay message Remove btnRemove message A program is needed to meet the following requirements Upon first load lblMessage should not be visible Make sure that you set the Visible property of lblMessage to be False in the Properties Window When the u
186. k on the grab handle with the left mouse button move the pointer in the direction you wish to go then when the control is the correct size release the mouse button Graphical user interface or the form s shown to the user at run time Hard coding is where the developer codes things like input information or parameters directly into the code rather than reading it from user input or from a file or from using things like functions Examples would be when the developer explicitly writes the Hard coding path of where a picture can be found into the program rather than using the function Application StartupPath or a set of valid passwords for a login rather than reading them from a file This is generally classed as lazy sloppy coding and should be avoided where possible i Capping is the convention you must use to name any objects or variables that you use within your projects i Capping means using upper case for the first letter of any words i Capping used in names with a prefix in lower case Examples of this is btnProcessData intProcesedinformationCount Notice the prefixes btn int are in lower case but the first letter of each word is in upper case Any variation on this theme is not acceptable NET has a number of functions that come as part of the package An inbuilt function is a word or phrase that does something specific when used in the correct context within code and cannot be used in any other context i e function names a
187. keyboard or use your mouse to click on the box alongside the Second Number prompt 100 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives User documentation Lecturer Jane Fletcher What do I enter the number you enter must be a whole number and in the range of 1 to 9999 Now look at Figure 3 You will see here that the numbers 72 and 27 moPiu totromsne rte have been entered into TwoPlusTwoO First Number What do do if enter the wrong number ere Don t panic You can either put the cursor to the right of the incorrectly typed number and press the Backspace key on your keyboard or you can click the black button on the form called pe Clear More on this later 00 Figure 3 Numbers entered in TwoPlusTwo Close Calculating the total Once you have entered both numbers then you should click the black button marked Process z TwoPlusTwo from SNC PLC You will see the total of your two numbers displayed in the red box beneath your entry For your convenience the numbers you entered are left displayed as shown in Figure 4 First Number 72 Second Number 27 What do I do if the answer is incorrect In the unlikely event of an error occurring you should contact the SNC PLC Technical Su
188. ks btnDone the program should examine the value in intUser and check to see if the correct passcode for that user has been entered using a Select Case statement For user 1 the passcode is 1111 for user 2 it is 2222 and so on a Declare a Boolean variable called bValid b Set the value of bValid to be false c For each case of intUser 1 6 if the passcode entered is correct set bValid to true 13 If the user enters a valid passcode i e bValid is True then the program should display Form2 and wait for the user to click that form s Return button If an invalid passcode has been entered then the program must display an error message in the form of a message box 14 The Return menu item on Form2 should dispose of Form2 and return control back to Form1 D 00 Jane Fletcher South Nottingham College pae O Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes Lecturer Jane Fletcher 13 0 Specification for program developed in class Using String Format Enter information 6 Product Price Ta rroduct Catalogue 8 TextBox ttPrice 9 Butoni btnAdd 2 E i ListBox1 lstCatalogue 1 Button2 btnDeleteSelected Button3 btnDeleteAll 6 GroupBox TextBox1 txtProduct D S Se 01
189. l permanently again click on the recumbent drawing pin and it F eee l will become upright and hold the Toolbox in place 3 aedi Before you do any work on your project you must save it in the location of your choice i e in the folder system you made back on pages 51 to 53 U A 56 Jane Fletcher South Nottingham College aeae aaa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Saving a project Lecturer Jane Fletcher Visual Studio has been set up on the College system to default to saving your projects in the Visual Studio 2010 folder in My Documents This can be very annoying if you ve already established your own folder system as explained in this document and want to save your projects somewhere else completely The following section will show you how to change your default settings for where your projects will be saved You do not HAVE to do this but it saves time and effort later on if you choose to do it 60 WindowsApplication1 Microsoft Vi Click on Tools in the menu bar a ee ae eee ata Tools Test Window Help ile Toolbox I Xf Forml vb Design Attach to Process Ctrl Alt P fae c g alia 2 aad i Connect to Database i eee From the Tools menu select Options u tag Add SharePoint Connection E Code Snippets Manager
190. l be able to readily find each project you have made within an easily identified folder specifically for this unit There are various ways of doing this the first and easiest way is to create a different folder for each week of the course and within each week s folder have separate folders for each different project Another way is to name your folders with a readily identified name that states the purpose of the project contained within it Below is a screenshot of the file structure adopted by the author of this document Note that the master folder is called 14 Event Driven Programming then there is a further folder called Weekly programs and thereafter there are folders for each week of the course E I4 Event Driven Programming Weekly programs nf Organize Share with a Jr Favorites E Desktop pi Downloads Recent Places Libraries Documents al Music fe Pictures E Videos JE Computer amp BOOTCAMP C cog Macintosh HD C ee Removable Disk is di 6 Software De di 14 Event Drive JO 120620 Timetat Ji Djanogly d Perel 28 tems 4 j Burn Mame Ji Week 01 Ji Week 02 Week 03 J Week 04 Ji Week 05 A Week 06 Ji Week 07 A Week 08 J Week 09 Ji Week 10 Ji Week 13 A Week 16 Ji Week 17 A Week 18 Ji Week 20 Ab Week 21 J Week 22 A Week 23 A Week 24 A Week 25 New folder Date modified 16 05 2012 08 28 16 05 2012 08 28 16 05 2012 0
191. l be presented with an entirely different development environment cxtviestsu e Which could cause panic Once you have clicked on the Start Visual Studio button you are entering the world of VB NET Fe eee 54 Jane Fletcher South Nottingham College yp aaee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Starting a new project Lecturer Jane Fletcher The next thing you will see is the Visual Studio 2010 Professional Start Page for the Visual Basic NET environment This screen is shown below Yours will not look exactly like this but will be very similar The section of the screen shown in the red circle below will be empty the first time you run Visual Studio because it is a list of your recently accessed projects You can see from the illustration below that the last project accessed on this computer by the author is one entitled prjPrintingFromAListBox When you have written a few projects you will find them listed in this area of the form It isn t always wise however to rely on this aspect of the software to enable you to find what you re looking for you re far better off having a robust file structure eo Start Page Microsoft Visual Studio File Edit View Debug Team Data Tools Test Window Help Tak Iie i IE EESE 2 9 O Gl gt ouaeee ol A a Ga oe M ad Toolbox 4 Gener
192. labels contained within it eee Surname lf you do not ensure that you have selected the GroupBox prior to the addition of other controls you may find that these new controls don t behave as if they are part of the GroupBox A good way of testing to see if the controls think they belong is to move the GroupBox if the controls within it move too then they are part of that Group To move the GroupBox select it and place the cursor in its top left hand corner Notice that a small icon with north south east and west pointers appear Hold the left mouse button down over this icon and move the GroupBox to where you want it to be Release the mouse button when you re there oY 19 Jane Fletcher South Nottingham College a mnm N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls GroupBox control Lecturer Jane Fletcher Commonly used properties of the GroupBox control BackColor Sets the background colour of the GroupBox The default background colour is determined by that of the form and it can be changed using the same method as that applied when altering the form s background colour Font Determines the size style and type of font to be used in the Text property of the GroupBox Clicking on the ellipses to the right of the Font property in the Properties Window generates the
193. le form of evidence For P2 learners must show that they are able to use event driven programming tools and techniques including those listed in the unit content A presentation would be a suitable form of evidence For P3 learners must design an event driven program The program only needs to be basic as suited to the level of learners but obviously this is at the discretion of the tutor and the individual learners The design should be clear and have no obvious errors For P4 learners must create the program they worked on for P3 This program should be fully functional and fulfil the design aims set down For P5 learners must develop and apply an appropriate test plan for the program they worked on for P4 The test plan should test functionality and demonstrate that the program fulfils the design aims and other requirements Evidence is likely to be in the form of a short report on the test plan and results illustrated with screen grabs For P6 learners must produce onscreen help for an event driven program The help screens must be coherent and laid out according to the standards that learners have previously been taught It is up to the tutor at this stage whether they wish to have learners use the work they have produced for P4 and P5 or to give learners a generic event driven program for which to write the appropriate help In order to gain a merit learners must achieve all the pass criteria and all of the merit criteria For M1
194. learners must discuss how an operating system can be viewed as an event driven application This will probably be the operating system that learners are working with but tutors may choose a different one if they wish As with P1 evidence should be a poster leaflet or short report but a presentation can also be used if the learner or tutor would prefer For M2 learners must justify their choice of tools and techniques used in the production of the event driven application created in P3 Evidence should be a short report or similarly detailed presentation For M3 learners must analyse the results of their testing in P6 The analysis should compare expected to actual results to identify discrepancies It would also be expected that learners would suggest what actions should be taken to resolve any problems shown up by the testing Evidence for this criterion should be a short report This could be an extension of the P6 report For M4 learners will create technical documentation for the support and maintenance of a computer program As with P6 it is up to the tutor whether they wish to have learners use the work a sOOSO ee 32 Jane Fletcher South Nottingham College l Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 1 Unit Specification Lecturer Jane Fletcher they have carried out for P4 and P5 or
195. lected esi ee 227 Jane Fletcher South Nottingham College lt _ lt 66642 H Unit 14 Event Driven Programming edexcel eee BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 16 Printing from a ListBox J Lecturer Jane Fletcher In order to print out the items from a ListBox control use the For Each Next construct In the Sample code below there are two nursery rhymes typed directly into the Items collection of the ListBox object lstRhymes When the user clicks the Button object btnPrint the PrintPreviewDialog object is referenced which calls the PrintDocument1 PrintPage function The output from the program looks like this This is the form once the program is running The File MenuStrip item contains only End which stops the program running When the Print button is pressed the PrintPreviewDialog object produces the following The code to make this happen is shown on the next 2 O0 BB B close Page 1 ee lt lt aiint t t t tC 8 Jane Fletcher South Nottingham College lt _ lt ua Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 16 Printing from a ListBox Lecturer Jane Fletcher Private Sub CloseToolStripMenuItem Click ByVal sender As System Object _ ByVal e As S
196. lege Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 1 Unit Specification Lecturer Jane Fletcher Assessment It is suggested that this unit is assessed using four assignments as summarised in the Programme of suggested assignments table Finding a scenario which covers all aspects of all criteria is difficult but the one suggested is acceptable It places the user in a role which is at an acceptable level for their experience which is important when devising assignments Some of the evidence required to complete the assignments could be naturally occurring within their work for other units within the qualification or for other courses they are undertaking and tutors are encouraged to use such evidence Evidence produced for this assignment can be used towards the evidence required for other criteria in this unit In order to gain a pass grade learners must meet all of the pass criteria For P1 learners must explain the features required to implement a given design This refers to the features section of the unit content for learning outcome 1 In order to achieve this criterion learners must describe the features clearly and logically showing they have recognised the underpinning principles and in particular the reasons why triggers and timing are important A presentation or leaflet would be a suitab
197. lege a mnm O Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers lt lt lt lt lt lt _ Lecturer Jane Fletcher intDaysDifference DateDiff DateInterval Day dtTodaysDate dtInvoiceDate e Focus should be placed in txtlnvoiceAmount 13 On the click event of btnProcess a Validate the user s input into txtInvoiceAmount as being a number in the range of 1 to 10 000 b Once the number is validated any non valid input should be rejected with an appropriate error message and the user returned to the text box for further input store the value in txtInvoiceAmount into the variable decilnvoiceAmountEntered c Alter the height of the form to display gbInvoicelnfo d Depending on the value of intDaysDifference calculate how much discount is to be allocated to the user i If the value is 14 or more then 10 discount is given ii If the value is O or more then 5 discount is given iii If the value is less than 0 then no discount is given e Store the appropriate discount rate in the variable intDiscountRate 10 5 or 0 e Display an appropriate message to the user in lblPaymentDateDifference e g You are paying the invoice 15 days early e Display the discount rate being given intDiscountRate in lblDiscountRate e Calculate the amount of discount to be gi
198. lly wish to delete everything MsgBoxStyle YesNo _ Are you sure If intResponse vbYes Then They want to delete lstHistory Items Clear End If txtNumber Focus End Sub End Class ee eee 9 Jane Fletcher South Nottingham College ymae 8 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons Lecturer Jane Fletcher Exercise 4 1 Process alje History Delete Selected Delete All History count ltem Object 1 Form GroupBox1 2 GroupBoxt 3 TextBox1 txtNumber 4 Button btnProcess 5 irowo ListBox1 stHistory Button2 btnDeleteSelected Bo Button3 btnDeleteAll Button4 btnClose 0 abel Label2 lblHistoryCount A program is needed to meet the following requirements When the program loads the entire form should be visible and the cursor placed in txtNumber When the user clicks btnProcess the program should validate the entry in txtNumber as being numeric and within the range of 1 to 100 Any illegal input should generate a message box displaying a suitable message the text within the text box should be deleted and the cursor placed into the text box ready for user input a a 30 Jane Fletcher South Nottingham College a mnm aN Unit 14 Event Driven Pr
199. lt i lt i i i i i 67 Jane Fletcher South Nottingham College a mnm Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Arithmetic and logical operators Lecturer Jane Fletcher OrElse The OrElse operator performs short circuiting logical disjunction on two Boolean expressions If the first expression in an OrElse expression evaluates to True then the second expression is not evaluated because it cannot alter the final result and OrElse returns True If txtFirstNumber Text lt 10 OrElse txtSecondNumber Text lt 10 Then lblOutcome Text One input is less than 10 End If If the user enters 5 into txtFirstNumber and 10 into txtSecondNumber OrElse will only evaluate the first condition it won t bother with the second one because the first one has fulfilled the OrElse and will return True If the user enters 10 into txtFirstNumber and 5 into txtSecondNumber OrElse will return True but will evaluate both conditions since the first one doesn t return True If the user enters 10 into both text boxes then OrElse will return False O A 68 Jane Fletcher South Nottingham College pama Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures Lecturer Jane Fletche
200. ltiline property of the TextBox is also set to True then text will wrap around onto the next line if the user s entry is too long to fit onto one line of the text box In the illustration below the first TextBox has its WordWrap set to False and Multiline as True whereas in the second illustration both WordWrap and Multiline are set to True Notice the difference The quick brown fox jumps over the lazy dog The quick brown fox jumps over the S 3 Jane Fletcher South Nottingham College paee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls RadioButton control Lecturer Jane Fletcher RadioButton The RadioButton control is accessed via the Common Controls section of the Toolbox by clicking on the icon shown here Toolbox vax o opgressna adioButton e A IC DOX abl TextBox on ToolTip RadioButtons are designed to work in teams that sit together within a f teve GroupBox control RadioButtons present the user with choices within a team of tows RadioButtons only one can be selected at any one time An example of when a team of RadioButtons might be used would be to select a flavour for a bottle of drink it would be either orange or lemon or cola but it can t be all three or two of the three I m sure it could be but w
201. lution Explorer window shown below 608 WindowsApplicationl Microsoft Visual Studio File Edit View Project Build Debug Team Data Tools Test Window Help ipDeGa d saBlalse2 9 e 4 Gld gt w a le es Debug meee Formli vb Design X Saag Solution Explorer All Windows Forms a FS 4 Common Controls R Pointer Button CheckBox Bo CheckedListBox E w re w qn e C A m w When you have right clicked a context menu will appear Left Lar ara 7 9 ar click on Add u peetertcnon Rebuild Form1 vb Clean A further context menu will appear once you have clicked Add Sees From this you should click Windows Form Rd Reference Add Service Reference ution Explorer amp View Class Diagram pand H Build ee ee Rebuild e 1 New N60 Wn a A You will be presented EF ae O J New ltem Ctrl Shift A Add at this stage with the cn pe csaa eens u Existing Item tri Add Reference A a Login Form Common hems oy a sate Add Service Reference n Explorer Add Form dialog box ea 5 MOS Parent Form Cimon Bi oD amp View Class Diagram Scroll down the list of 0 BI Report iii 3 User Control Debug gt pplication1 Project P EE Report wizard Common Items a Component 23 Add Project to Source Control b available templates Btn oe o few and click Splash _ a Screen then click i ae the Add button o A 80 Jane Fletcher South Nottingham Colleg
202. m intYear As Integer dtToday Year Dim dtChristmas As Date New Date intYear 12 25 Dim intDay As Integer Dim strDay As String The font of the menu strip should be the same as the font on the form The menu strip should have one item at the top level File File should contain two items New and Exit Exit should close the program New should reset the form to its original condition the label lblMessage should be cleared of its text and the date of the datetimepicker dtpSelectedDate should be set to today s date 10 Upon the Form_Load event set the background colour of the menustrip to be white and the foreground to be black Also on the Form_Load event the program should work out the day of the week held in the current system date This value should be stored in the variable intDay See 1 intDay Date Today DayOfWeek 12 The correct name of the day should be determined by doing a Select Case operation on the value contained in intDay If intDay contains 1 then the day is Monday and so on The result of the Select Case should be stored in strDay 13 Once the day has been established the present date should be displayed in the label lblTodaysDate in the format strDay amp amp Date Today 14 The CloseUp event of a DateTimePicker control is activated when the DateTimePicker has been used and subsequently closes up On the CloseUp event of dtpSelectedDate the date value of the DateTimePicker s
203. mCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Making a project look more professional Lecturer Jane Fletcher By the time that you have got into the second semester of this course you should be aiming towards producing projects that look and to work in a professional way This means having no bugs within the logic ensuring that the tab order is correct on each form and appropriate help facilities and error messaging available to assist the user in the operation of the software What do you notice when you load any Microsoft software such as Word Excel PowerPoint Access Visual Studio etc Each of the individual parts of the Office suite have their own individual start up screen or as it is known in the trade splash screen The idea behind the splash screen is to tell the user what the software is that is loading and to give the user something to look at while the software itself loads Creating splash screens There is a template splash screen available to the developer once a new project has been Started However there is a considerable amount of coding attached to this screen that you may not want to use so be prepared to edit heavily when you re in the coding view To load a splash screen template there are several methods available but the two easiest ways will be explained here Method 1 using Solution Explorer Right click on the project s name in the So
204. mCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Lecturer Jane Fletcher What is structured English Structured English is a language that comes between ordinary English and program code and is written using real English verbs rather than Visual Basic NET keywords Structured Plain English Pseudocode Program code English User Systems Analyst Programmer In the real world depending on the size of the company and the number of employees in the IT systems development department these tasks would be performed by different people First of all either the project manager or the systems analyst would work with the user s to establish the requirements of the new system The systems analyst would then write a Requirements Specification which is the plain English part of the above process In this document the full specification for the system including form and report designs could be laid down and signed off by the user The user signing off is an extremely important part of the process since it means that you have proof of what the user wants if it comes to a point later on in the development process when the user claims that he or she asked for something different to what the developers have produced The programmer or developer the terms are interchangeable will then take the project specification and from that create either structur
205. mber amp amp decTotal Increase the size of the form Me Height 546 End Sub ees Jane Fletcher South Nottingham College y auae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Private Sub radMultiply CheckedChanged ByVal sender As System Object _ ByVal e As System EventArgs Handles radMultiply CheckedChanged Lecturer Jane Fletcher The user wants to multiply the two numbers decTotal intFirstNumber intSecondNumber lblAnswer Text intFirstNumber amp amp intSecondNumber amp amp decTotal Increase the size of the form Me Height 546 End Sub Private Sub radDivide CheckedChanged ByVal sender As System Object _ ByVal e As System EventArgs Handles radDivide CheckedChanged The user wants to divide the two numbers decTotal intFirstNumber intSecondNumber lblAnswer Text intFirstNumber amp amp intSecondNumber amp amp decTotal Increase the size of the form Me Height 546 End Sub End Class ee e ee Jane Fletcher South Nottingham College pae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Lectu
206. mbers have been entered the user should be allowed to click a button see previous paragraph which should validate the user s input Should the input be valid then both numbers should be added together and the result stored in an integer variable intTotal The value in intTotal should then be displayed to the user in lblMessage in the format FirstNumberEntered SecondNumber Entered intTotal There should be another button available which allows the user to remove the displays and to reset the screen to its original state This button should clear the label s Text property the Text properties of both text boxes should be blanked out and the cursor s focus put into the first text box KO t SS es 84 Jane Fletcher South Nottingham College oS aaa a 50 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Design documentation Lecturer Jane Fletcher There should be a second button available to allow the user to close the software Once the button to close has been clicked a messagebox should be displayed to the user saying Goodbye and the project should close Inputs to the project First integer into the text box used for this purpose intFirstNumber Second integer into the text box used for this purpose intsecondNumber Outputs Total of both numbe
207. ming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher A program is needed to meet the following requirements Overview 1 When the program loads the entire form should be visible 2 Throughout the program use the font of your choice 3 The program needs these variables declared at the top of the program Dim dtTodaysDate As Date Date Today Dim intDay As Integer dtTodaysDate DayOfWeek Dim dtStartDate dtEndDate As Date Dim intDaysDifference As Integer The font of the menu strip should be the same as the font on the form The menu strip should have one item at the top level File File should contain two items Clear and Exit Exit should close the program Clear should reset the form to its original condition the label lblMessage should be cleared of its text and the date of the two datetimepickers should be set to today s date dtpEndDate should be disabled 9 Upon the Form_Load event set the background colour of the menustrip to be white and the foreground to be black 10 Upon Form_Load dtpEndDate should be disabled 11 0n the Form_Load event the correct name of the day should be determined by doing a Select Case operation on the value contained in intDay If intDay contains 1 then the day is Monday and so on The result of the Select Case should be stored in
208. ming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development EG Lecturer Jane Fletcher Notes U O VI Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Introduction to the Unit Lecturer Jane Fletcher This unit is the first one that you will do that includes any programming It runs over the entire academic year i e 36 timetabled weeks and each lesson lasts for one hour and a half You will have to write down lots of program code so it is a good idea to have with you a pen and some lined paper for each of these lessons later on you may wish to use a computer to take notes but to start with pen and paper is best Needless to say all classes will start exactly on time and if you are late then you will miss some vital explanations and will have to catch up on your own time Structure of the classes During the course of each lesson you will be shown how to write one program afterwards you will write the program just demonstrated yourself using your own notes and the program specification available separately on the network and again in this booklet Once you have done that and got a bug free piece of software to demonstrate to your lecturer you will be asked to move on to write Programming Exercise One for th
209. mment to explain the logic and is ignored by the program compiler It is there purely to aid understanding of the purpose of the logic for the reader In this case the statements are very simple and each line doesn t really need a comment but it is good practice to get into the habit of richly commenting your program code In months to come you will appreciate the effort you made when you look back at code you have written for an example of how to write certain Statements for example The black writing indicates that this text represents either an object within the code lblMessage for example or a reserved word black or white for example The brown writing indicates that this is a programmer defined literal i e it is in double quotation marks and whatever appears between these quotation marks is what will show in this case in the label lblMessage These four VB statements will always occur and will always occur in the order stated above The only way that these statements will ever occur in a different order is if the programmer decides to move any of the lines of code lll GK ssSSS 69 Jane Fletcher South Nottingham College a mnm Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Control Structures Lecturer Jane Fletcher Selection A selection is a choice
210. mmonly used Properties of the PictureBox control BorderStyle What the borders of the PictureBox will look like at run time Options are None the default FixedSingle a line drawn around the edge of the PictureBox and Fixed3D an embossing effect around the edges of the picture Dock Where the image will be placed in its host object if this property is set to anything other than None see above Enabled Whether or not the PictureBox is active if there are any functions based around the PictureBox like a Click event and this property is set to False then the event function will not be accessible The reverse is true if this property is set to True Image The location of the image to be uploaded at run time to this PictureBox object SizeMode Options available are Normal Stretchlmage AutoSize Centrelmage and Zoom If you want the image you re uploading to fit to size then you should select Stretchlmage There may be some aspect ratio distortion if you do this however ea A 37 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls TabControl control Lecturer Jane Fletcher TabControl The TabControl object gives you an array of pages upon which you can place other objects When the corresponding tab is clicked by the
211. n s label The default value is MiddleLeft but each of the choices available to the Label object is available here Visible Set to either True or False determines whether the RadioButton and its associated label are visible or not Can be changed at either design time or run time ee a 5 Jane Fletcher South Nottingham College y aaee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls CheckBox control Lecturer Jane Fletcher C h e C k B OX All Windows Forms E Common Controls The CheckBox control is accessed via the Common Controls section of the Pointer Toolbox by clicking on the icon shown here owes CheckedListBox Like RadioButtons CheckBoxes are generally grouped together in a GroupBox but are not mutually exclusive so it isn t so important to get them working together as a team as it is with RadioButtons It is quite possible to put CheckBoxes into the same GroupBox as RadioButtons since they won t interfere with each other in terms of only one being allowed to be active The way to get a button onto your form is to click on the CheckBox icon in the Toolbox as above and move across to the form with it You will notice that the cursor changes at the point of entering the vicinity of the form from a pointer to a plus sign with a small imag
212. n t a number Display a messagebox saying You must enter a number in the range of 1 to 100 in the first box Blank out the text in txtNumber Set the cursor focus to txtNumber 1 Quit the subroutine End If Set intNumber1 to hold the value contained in txtNumber1 Check the range entered by comparing intNumber1 with 100 and 1 if it is outside that range then Display a messagebox saying You must enter a number in the range of 1 to 100 in the first box Blank out the text in txtNumber1 152 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips _ _ _ _ _ ae Lecturer Jane Fletcher Set the cursor focus to txtNumber Quit the subroutine End If Check that there is no decimal place contained in txtNumber 1 if there is then Display a messagebox saying You must enter an integer in the range of 1 to 100 in the first box Blank out the text in txtNumber Set the cursor focus to txtNumber 1 Quit the subroutine End If If the length of the entry in txtNumber2 0 Then Display a message box saying You must enter a number in the second box Set the cursor focus to txtNumber2 Quit the subroutine End If If the length of the entry in txtNumber2 is gt 3 Then Display a messagebox saying You must enter a num
213. n the click event of btnClear in this order a Ask the user if they really want to delete everything via a YesNo message box b If the answer is yes then clear the list box of all entries c Perform the subroutine CheckForEntries d Put the cursor into txtName 13 On the click event of lstName a Change the background colour of btnUpdate from red to blue b Change the background colour of btnProcess from blue to red Output from this program will read MULTIPLICATION CORNER our multiplication table n ee 220 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Lecturer Jane Fletcher Coding for this program Public Class Form1 Dim intPointer As Integer Private Sub Form1_Load sender As System Object e As System EventArgs Handles MyBase Load Set the defaults for the program MenuStrip1 BackColor Color White CheckForEntries End Sub Private Sub CloseToolStripMenuItem Click sender As System Object e As System EventArgs _ Handles CloseToolStripMenuItem Click End the program Me Dispose End End Sub Private Sub btnProcess Click sender As System Object e As System EventArgs _ Handles btnProcess Click Check that the use
214. nce DateDiff DateInterval Day dtSelectedDate dtChristmas If intDaysDifference Then lblMessage Text It s CHRISTMAS ElseIf intDaysDifference lt 1 Then lb1lMessage Text It s amp intDaysDifference 1 amp days since Christmas Else lblMessage Text dtSelectedDate amp is amp intDaysDifference amp days to Christmas End If End Sub Private Sub NewToolStripMenuItem_Click sender As System Object e As System EventArgs _ Handles NewToolStripMenuItem Click Get rid of the contents of the label lblMessage Text Reset the datetimepicker to be today s date dtpSelectedDate Value Date Today End Sub End Class Fee 64 Jane Fletcher South Nottingham College 2_ _ SL SG 5 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher Exercise 8 1 Using Date TimePickers Ex File Todays date Monday 26 11 2011 EJ f November 2011 7 8 6 End date EE Item Object Item Object N e A l C L 2 MenuStrip1 File 7 Label3 lblTodaysDate 3 ClearToolStripMenultem 8 DateTimePicker1 dtpStartDate ExitToolStripMenultem 9 DateTimePicker2 dtpEndDate Label1 Label4 lblMessage eee 65 Jane Fletcher South Nottingham College pae 4 a Unit 14 Event Driven Program
215. nd gbMSFlavours Uncheck chkMilk chkSugar and chkSweetener Disable btnUpdateOrder btnClearSelected When the user clicks btnClearSelected the program must make sure that the user has actually selected something in lstYourOrder If they have then that entry should be deleted btnClearAll When the user clicks btnClearAll the program must ask the user if they are sure that they wish to delete the entire contents of the list box via a message box If the user answers yes then the contents of the list box must be deleted pC 14 3 Jane Fletcher South Nottingham College p ua Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Je ae Lecturer Jane Fletcher Then Enable chkMilk disable gbCoffeeType gbExtras and gbMSFlavours Uncheck chkMilk chkSugar and chkSweetener Disable btnUpdateOrder btnClose When the user clicks btnClose the entire program should end CCG 144 Jane Fletcher South Nottingham College Sa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips Lecturer Jane Fletcher 6 0 Specification for program developed in class Week 7 Exercise in class Answer is 4 _ _ CloseToolStripMe
216. nd the Pointer it is probably the most used control It is used to prompt and enable the user to perform some processing on entered information Pater tT gu mT mT Lr C1 ci to Di The way to get a button onto your form is to click on the button icon in the a Toolbox as above and move across to the form with it You will notice that the cursor changes from an arrow pointer to look like a plus sign with the button icon attached to it When you re in the location where you want to p place the button press the left mouse button and drag the resulting rectangle 9 Butoni shape to the size that you wish the button to be You can move the button or lt resize it using the grab handles located around the outside of the button shape Notice that the text in the centre of the button contains the default name of this button object the default name is Button1 with the next button used on the form having a default name of Button2 and so on Notice that when you alter the name of the button object in the Properties Window the text remains the same until you alter the Text property of the button In the example alongside you will see that the Text property of our button has n l ae been changed in the Properties Window to Display Message To do this make EL sure that the button is selected click once on it and notice that the grab handles will appear this shows that the object has been selected and then
217. nder As System Object e As System EventArgs _ Handles btnUpdate Click Change the AcceptButton of the form to btnUpdate Me AcceptButton btnDone The user must have selected something in the list box to be allowed to do this so check to make sure that they have If lstName SelectedIndex gt 1 Then Else MsgBox You must select a name from the list before continuing _ MsgBoxStyle Critical ERROR Exit Sub End If Disappear the current group box so that the user can t click something in error gbAdd Visible False Set the pointer to equal the current place in the list box intPointer lstName SelectedIndex Put the text to be updated in the text box of the update groupbox txtUpdatedName Text lstName Items Item intPointer Enable the update list box gbUpdate Visible True gbUpdate Enabled True txtUpdatedName Focus btnProcess BackColor Color Blue btnUpdate BackColor Color Red End Sub Private Sub btnDone Click sender As System Object e As System EventArgs Handles btnDone Click Update the entry in the list box with the new information after it has been validated by the same rules If txtUpdatedName Text Length Or txtUpdatedName Text Length gt 20 Then MsgBox Your entry should be text up to 20 characters in length _ MsgBoxStyle Critical ERROR txtUpdatedName Text lstName SelectedItem txtUpdatedName Focus Exit Sub End If Remove the old item lstNam
218. ne Fletcher TabIndex The VB NET Editor gives each object placed on the form a Tablndex relative to when it was placed at design time the first object put onto the form gets a Tablndex of 0 the second has a Tablndex of 1 and so on The Tablndex determines the order in which control is passed on the form at run time when the user presses the Tab key Ideally the tab order of a form should start where the cursor needs to be placed when the form loads and working its way up to the last field the user has to fill in on the form in that order It is pretty much guaranteed that the programmer will get the order of placement wrong in the first instance if the tab order of a form is incorrect then the programmer can manually alter the Tablndex properties of all controls to ensure that the lowest number i e 0 is given to the first place the cursor should go working up to the final place where the user needs to be to enter information onto the form with this object having the highest number in its Tablndex property Any objects that don t require user input like a prompt for instance can be given a Tablndex of 100 It doesn t matter to VB NET if higher numbered TabIndexes are duplicated Text The words that appear in the centre of the button Be succinct ensure that all of the text is visible and never ever use bad language TextAlign Text within a button can be displayed maces a using any form of alignment selected by TextImageRelation us
219. ne Fletcher Commonly used Properties of the TabControl object DrawMode Allows the developer to change the colours of the tab if this property is set to OwnerDrawFixed If this property is not changed from its default value of Normal then the appearance of the tab cannot be changed Font The font size and style that will appear in the tab TabPages This is a Collection of pages that will fit within the one TabControl See above for a longer description on the use of this property aal 4 0 Jane Fletcher South Nottingham College p e Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Timer control Lecturer Jane Fletcher Timer The Timer control is accessed from the Components section of the Toolbox by clicking on the icon shown here It is the last one of the Components Rm Pointer section The way to get a Timer control onto your form is to left click on a ipa e l DirectoryEntry the icon in the Toolbox then move across to the form and left click once on TA DirectorySearcher the Form object The Timer control does not appear on the form itself Fero wherever you choose to place it on the form it will always move and will E FileSystemWatcher A appear in the grey area below the Form ae File Edit View Project Build Debug Team Data Format Tools Test Window Help k
220. ng learning changing lives Example programs 6 MenuStrips Lecturer Jane Fletcher Click event for File gt Exit Dispose of the form End the project End of FileExit_Click Click event for File gt New Perform the Subroutine ClearStuff End of FileNew_Click Subroutine ClearStuff Set the Text properties of txtNumber1 and txtNumber2 to equal Set the Text property of lblAnswer to equal Set the values in intNumber1 intNumber2 and decTotal to equal 0 Set the height of the form to equal 182 Enable the GroupBox gbNumbers Enable the GroupBox gbOperator Set the cursor focus to be on txtNumber1 End of ClearStuff Click event for Help Bring to the front gbAbout Set gbAbout to be visible Save the height of the form in its present state into intSaveHeight Set the height of the form to equal 389 End of Help_Click Click event for btnReturn Send gbAbout to the back Set gbAbout to be invisible Set the height of the form to equal the value stored in intSaveHeight End of btnReturn_Click fT 154 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 7 Number processing with variables Lecturer Jane Fletcher 7 0 Specification for program developed in class Lowest number entered Highest number entered Lat Total of numb
221. nge of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine End If Set the height of the form to be 284 Bring the group box gbOperator to the front Disable the group box gbNumbers End of btnProcess_ Click Click event for File gt Exit Dispose of the form End the project End of FileExit_Click Click event for File gt New eH e_ Jane Fletcher South Nottingham College SSSS Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Perform the Subroutine ClearStuff Lecturer Jane Fletcher End of FileNew_Click Subroutine ClearStuff Set the Text properties of txtNumber1 and txtNumber2 to equal Set the Text property of lblAnswer to equal Set the values in intNumber1 intNumber2 and decTotal to equal 0 Set the height of the form to equal 182 Enable the GroupBox gbNumbers Enable the GroupBox gbOperator Set the cursor focus to be on txtNumber End of ClearStuff Click event for Help menu item Store the current height of the form in the variable intSaveHeight Set the height of the form to equal 389 Set the GroupBox gbAbout to be visible Bring the GroupBox gbAbout to the front End of Help_Click btnReturn_Click Set the height of the form to equal the value stored in int
222. nly used controls TabControl control Reset any Graphics rotation e Graphics ResetTransform Lecturer Jane Fletcher Finally we should Dispose of our brushes FillBrush Dispose TextBrush Dispose End Sub This will all be explained more fully later on in this document when you will actually write a program that uses the TabControl object see Exercises 10 0 and 10 1 The way that different pages are added to a TabControl is via its TabPages property This can either be done at design time or run time In the example below we are going to add some tab pages at design time a ax TabControll System Windows Forms TabCont eit ae Bet al Within the Properties Window for the TabControl click on the TabPages rotis no RightToLeftLayout False property and then on the ellipses that will appear to the right of the sowtosrriss rase collection Click on the ellipses The TabPage Collection Editor will ssi smi appear as shown in the illustration below Notice that the properties are a co lection a displayed in category order you can alter this to alphabetical order if you a it by clicking on the A Z button To the left of this form you have wee ms P TabPage Catlection Edt a panel that lists the two TabPages that are currently neee aana within this TabControl We are going to alter them to da a peaa tbChoice1 and tbChoice2 with Text properties
223. nt Center sf LineAlignment StringAlignment Center If we are currently painting the Selected TabItem we ll change the brush colors and inflate the rectangle If CBool e State And DrawitemState Selected Then FillBrush Color Color wWhite TextBrush Color Color Black ItemRect Inflate 2 2 End If Next we ll paint the TabItem with our Fill Brush e Graphics FillRectangle FillBrush ItemRect Now draw the text e Graphics DrawString CurrentTab Text e Font TextBrush _ RectangleF op Implicit ItemRect sf ee e 82 Jane Fletcher South Nottingham College y mnm Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls Lecturer Jane Fletcher Reset any Graphics rotation e Graphics ResetTransform Finally we should Dispose of our brushes FillBrush Dispose TextBrush Dispose 7 Upon form load the foreground colour of the menu should match that of the form 8 For each of the radio buttons CheckedChange event a If the Checked property of the radio button is True i Set the Selectedindex property of tbMenu to be equal to For tbIntro 0 For tbChoice1 1 For tbChoice2 2 For tbChoice3 3 For tbChoice4 4 OK WN ii display a message in lblMessage to display a message saying The user has selected tab f
224. nters too many characters over 20 into txtSurname To see that lblMessage displays Jane Fletcher welcome to programming a To see that lblMessage displays Peter Rabbit welcome to opoo ee To check that the message is displayed in lblMessage a lblMessage txtForename and _ txtSurname are Notice that there are 12 tests planned for this very simple program This is NOT overkill and programming with the appropriate name 11 Click cleared and focus is put in txtForename should point you in the direction of how many tests you should be performing when you are Test btnRemove btnDisplay btnClose Group Why Num To check that the message is removed from testing your programs Structured test plan Designing the test data to be put into your program is just the first part of the testing procedure The next stage is to take that test data and to implement it within a plan Just having the plan isn t enough however you have to prove that you have implemented it Demonstrating proof can be done in one of two ways the first way is to put the proof within the Structured test plan itself in the column headed Actual result in the form of screen shots see over the page the second way is to include the screen shots in a numbered list after the test plan er es seselalesesSSeeSeeS 107 Jane Fletcher South Nottingham College pame 0 a Unit 14 Event Driven Programming SouthNoitinghamCollege BTEC Exten
225. nultem 13 GroupBox3 gbAnswer GroupBox1 gbNumbers Label1 lblAnswer e Buttont Button9 et FT z GroupBox2 gbOperator S amp _ Buttont0 btnPlus a S Button11 btnMinus 145 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 6 MenuStrips Lecturer Jane Fletcher A program is needed to meet the following requirements Overview 1 When the program loads only gbNumbers should be visible with the height of the form adjusted accordingly 2 The program needs these variables two integers intFirst and intSecond a decimal decAnswer a Boolean bFirst and a string strOperator These should all be declared at the top of the program 3 The variable bFirst should be set to True 4 The background colour of the menu strip should be set to be the same as the background colour of the form The font of the menu strip should be the same as the font on the form The menu strip should have one item at the top level File File should contain two items New and Exit Exit should close the program New should reset the form to its original condition the height should be adjusted and all objects that have had their Enabled property altered during the execution of the program should be reset ee i Using the program 10 Once the
226. number MsgBoxStyle Critical Not numeric txtNumber Text txtNumber Focus Exit Sub End If decNumber Val txtNumber Text If txtDecimalPlaces Text Length Then MsgBox You must enter something MsgBoxStyle Critical _ No entry made for number of decimal places txtDecimalPlaces Focus Exit Sub End If ene Jane Fletcher South Nottingham College y aaee O Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 9 Formatting numbers If txtDecimalPlaces Text Length gt 4 Then MsgBox You can have up to four decimal places MsgBoxStyle Critical _ Too much information in number of decimal places txtDecimalPlaces Text txtDecimalPlaces Focus Exit Sub End If Lecturer Jane Fletcher If Not IsNumeric txtDecimalPlaces Text Then MsgBox You must enter numbers in number of decimal places MsgBoxStyle Critical _ Numbers only please txtDecimalPlaces Text txtDecimalPlaces Focus Exit Sub End If intNumberOfDecimalPlaces txtDecimalPlaces Text If intNumberOfDecimalPlaces lt Or intNumberOfDecimalPlaces gt 4 Then MsgBox You can have from to 4 decimal places MsgBoxStyle Critical _ Value out of the accepted range for decimal places txtDecimalPlaces Text txtDecimalPlaces Focus Exit Sub End If lstOutput Items Add You wanted
227. o Until intTotal gt intSecondNumber intTotal intFirstNumber intCounter 1 Loop 1 Do Until Loop _o E eee a Do Until Loop ee Number to add Number to add up to Number to add Number to add up to 5 5 5 33 The loop was The loop was performed 6 times Still lazy programming U i lt lt lt i CSCti s SOCS 77 Jane Fletcher South Nottingham College paee 80 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Validation techniques Lecturer Jane Fletcher When you are creating your projects initially you will pay lots of attention to the cosmetic appearance of your work you will experiment with colour font line up and layout all this is completely proper and what you should be doing However when you get further on in your development of software it will become important that you ensure that all information that is entered by the user into your projects is correct There are different ways of ensuring validation is thorough when you are writing your projects The first way is to ensure that you use the appropriate data types when collecting data from an input object such as a TextBox and assigning it into a variable We have already explained about the different data types that are available to you when you are assigning data
228. o use the tools and techniques of an event driven language Triggers eg key press alarm system event touch screen event mouse click Tools and techniques eg use of tool boxes and controls selection loops event handlers triggers objects and object properties menus debugging tools Variables declaring variables scope of variables constants data types ee 30 Jane Fletcher South Nottingham College l Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Appendix 1 Unit Specification Lecturer Jane Fletcher 3 Be able to design event driven applications Specification input output processes user need purpose Design selecting and assigning properties to screen components data storage event procedures and descriptions appropriate ways of representing the processing tasks 4 Be able to implement event driven applications Creation of application use of development environment debugging data validation error handling and reporting Programming language syntax eg selecting declaring and initialising variable and data structure types and sizes Constructs selection eg if then else CASE iteration eg while do repeat until Programming standards eg use of comments code layout indentation Testing test strategy test plan structure eg test date expected result actual result corrective ac
229. o you need a way to SS distinguish one from another Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Saving a project Lecturer Jane Fletcher A project s prefix is prj You should always use the i capping rule for naming your project In this example we are going to call our project prjWeekOneProgramDonelnClass Notice that each of the words in the above name start with a capital letter thus following the i capping rule Prjweekoneprogramonedoneinclass would be perfectly acceptable to VB NET but it is NOT acceptable within the realms of this course Type prjWeekOneProgramOneDonelnClass into the text box alongside the prompt Name Save Project lle Name pr WeekOneDonelnClass Location C Users Jane Documents Unit 14 Event Driven Prograrmming Weekly Programs Week O1 Exercise Browse Solution Name pr WeekOneDonelnClass Create directory for solution Add te source control Notice that the Solution Name text box defaults to the same name as the project name You can change this if you wish but it is good practice to leave it the same name Notice also that there is a check box ready checked that will allow VB NET to create a directory for the solution Leave that checked Do not check Ad
230. ogramming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons _ VY YHHJyY JSSHo Lecturer Jane Fletcher Once the number has been validated it should be added to lstHistory The text box must be cleared and the cursor must be placed in the text box ready for user entry One should be added to intHistoryCounter see below and that counter should be displayed in lblHistoryCount When the user clicks btnDeleteSelected the program must make sure that the user has actually selected something in lstHistory If they have then that entry should be deleted One should be subtracted from intHistoryCounter see below and that counter should be displayed in lblHistoryCount When the user clicks btnDeleteAll the program must ask the user if they are sure that they wish to delete the entire contents of the list box via a message box If the user answers yes then the contents of the list box must be deleted the contents of the text box deleted and the cursor placed in the box ready for user entry intHistoryCounter see below must be set back to zero and then displayed in lblHistoryCount When the user clicks btnClose the entire program should end The program should use an integer variable called intNumber to receive the input from the text box after validation There should be another integer variable c
231. oject Settings H Source Control button Once you have done this the Options dialog box will show you that your User item templates location wbstaff 03 staff jane fletcher Wisual Studio 2010 Templates ltemTempl Text Editor M Always show Error List if build finishes with errors new location has been selected Debugging IV Track Active Item in Solution Explorer IntelliT race MV Show advanced build configurations Performance Tools Database Tools H FH Tools HTML Designer Office Tools Test Tools Text Templating d M Always show solution Save new projects when created V warm user when the project location is not trusted Show Output window when build starts l Prompt for symbolic renaming when renaming files Click the OK button to continue You will still have to make sure that you select the correct week s folder when you M Showalsstinas o Cancel save for the first time which will be explained below You should now be back at the Visual Basic NET design view You haven t yet saved your project you have just set the default location path for when you actually DO save File Edit View Project Build Debug Team Data To save your project click on File from the menu bar and then Save J res ae 99 iip New Team Project f All a New File j gl Open Project Ctrl O 7 Open Web Site Shift Alt O The Save Project dialog box will now op
232. ol object Name The prefix for the Timer object is tmr Enabled The default value for the Enabled property is False Set this property to True when you want the Timer object to be active Interval The default value for the Interval property is 100 which equates to 1 10 of a second One second requires the Interval property to be set to 1000 five seconds requires an Interval setting of 5000 and so on a 42 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls ToolTip control Lecturer Jane Fletcher ToolTip The ToolTip control is accessible via the Common Controls area of the Toolbox The ToolTip doesn t have to be placed on a form but can be defined within the code either method works just as well The author s preferred method is to declare within the code If you choose to click on the Tooltip item in the Toolbox s Common Control menu then place it on the form but it will go to the grey pane beneath the Form object s template FA pN Bis E gt gt MenuStrips ee The purpose of the ToolTip object is to display context sensitive information to the user at run time Microsoft Visual Studio has useful ToolTips as shown in the screenshot below ss The ToolTip object here ip i I a a activated when the user in Ar B
233. ollowed by the text of the selected tab The code for this is lblMessage Text The user has selected tab amp _ tbMenu SelectedTab Text amp b If the Checked property is false set the text in lblMessage to be blank nM 183 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming SouthNoitinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Example programs 11 Creating Web Browsers 11 0 Specification for program developed in class File Enter URL Take me there SouthNottinghamCollege SNC Home Full Time Courses Part Time Courses 14 16 Provision University Level Employers NTN AWARDS JAN 2012 Contact us on 0115 945 7260 www snc ac uk snctraining A pan About Us Student Support Automotive Academy TU Education _ Interested in full time courses Apply for a full time course here Latest News College Named Training Provider of the Year South Nottingham College s business development division SNC Training has oe a a range of prospectuses to help you choose been named Training Provider of the Year at the right course for you the Nottingham Training Network NTN awards on 26 January 2012 Browse a prospectus here SNC towaz TRAINING _ Course Guide Read More Take a look atthe new Part Time A Z Prospectus click Apprenticeship Week here YH We are hosting an event
234. opCenter UscMremeric fextlign Jetermines the position of the 4 Text Now the label will grg Text amp lign To R j h t i sreseas ei nenien aa p g UseMnemonic UseWaitCursor Visible TextAlign And so on Now the label will grow vv UseMnemonic UseW aitCursor Now the label will grow ee 16 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Label control Lecturer Jane Fletcher Commonly used properties for the Label control AutoSize This property has a default value of True A label that has an AutoSize set to true will grow to fit the text that the developer puts in its Text property However should the label contain a large amount of text it may possibly extend beyond the right hand edge of the form since it isn t possible to wrap text in a label with AutoSize set to True There are no grab handles on an auto sized label so it isn t possible to stretch it to fit the text it is to hold Setting this property to False allows the programmer to set the size border style and alignment of the text it is to contain BackColor Sets the background colour of the label The default background colour is determined by that of the form and it can be changed using the same method as that
235. or IT Practitioners Software Development advancing learning changing lives INDEX Lecturer Jane Fletcher P PictureBox ii 9 40 41 42 Pointer 4 13 Process 4 96 111 112 113 114 115 169 Program specification 4 102 Properties Window 3 4 6 7 11 12 13 14 15 16 18 19 20 21 22 24 28 31 33 34 37 40 44 46 122 R RadioButton i 8 26 28 29 30 Reserved word 4 Run 4 Run time 4 S Saving ii Selection iii 77 249 Sequence iii 76 Solution Explorer 4 6 7 50 66 67 87 SplashScreen iii Storage 4 String 71 78 152 158 173 174 198 205 207 211 214 216 217 219 222 224 225 238 240 242 Structured English iv 98 101 103 163 Subroutine 4 106 165 230 Subtraction 72 Syntax 4 System vi 1 5 11 36 43 85 123 126 130 131 132 138 139 146 147 148 158 159 168 169 174 175 179 183 190 198 199 205 207 208 209 212 216 217 224 225 226 233 234 235 236 242 248 T TabControl ii 9 43 44 45 47 188 193 Technical documentation 5 108 Testing iv 5 245 TextBox i 8 23 24 25 85 86 Timer ii 9 35 46 47 88 89 ToolTip ii iv 48 49 90 ToolTips 48 180 201 Trigger function 5 U User documentation iv 5 User interface 5 248 V Validation iii Variable 5 96 S 241 Jane Fletcher South Nottingham College jE LLL
236. orm 7 Also on the form load event the subroutine CheckForEntries should be performed The subroutine should be separate from other routines but should be positioned before the End Class statement of the program JAUN This routine checks to make sure that there are some entries in the list box Dim intCount As Integer intCount lstName Items Count If intCount gt Then There are entries so enable all the buttons that apply to the processing of the data in the list box btnRemove Enabled True btnUpdate Enabled True btnClear Enabled True Else There are no entries in the list box so disable everything btnRemove Enabled False btnUpdate Enabled False btnClear Enabled False End If 8 The click event for btnProcess should and in this order a Validate the entry made by the user in txtName as being in existence but being less than 21 characters Any deviation from this should be reported to the user by use of a message box and the subroutine exited with the text in txtName being removed and the cursor placed back there to await further input b Correct input should be added to lstName c The entry made in txtName should be removed and the cursor placed back there to await further input d Subroutine CheckForEntries should be performed 9 The click event for btnUpdate should and in this order a Set the accept button for the form to be btnDone el es se i _sSsSse_esNesSeeeSS 218 J
237. ormat txtProduct Text _ Format decPrice Currency d Both text boxes should be cleared of input and the cursor placed in txtProduct to await user input 6 btnDeleteSelected should check to see that the user has selected any line within the list box by examining the list box s Selectedindex property If nothing has been selected then a message box should be displayed to the user telling them that they must pick a line to delete If a line has been selected then it should be deleted and the cursor put back into txtProduct to await user input ee eeses s s _OSOSsSsSsSseeeSSSeeeSsS 202 Jane Fletcher South Nottingham College pae 666 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes Lecturer Jane Fletcher 7 btnDeleteAll should first check to see that there are some items in the list box by examining the list box s Count property If there is nothing in the list box then the user should be given an appropriate error message via a list box Should there be data in the list box then the user should be asked via a message box if they wish to delete all their catalogue of data If the response is yes then the list box should be cleared of all input In either case the cursor should be returned to txtProduct to await user input c
238. osition to where the Timer g object would go see the illustration to the right here Der Toolbox ix 4 Menus amp Toolbars k Pointer E ContextMenuStrip StatusStrip 68 ToolStrip am jal a Ww a al k Notice the wording Type Here greyed out in the top left hand corner of the MenuStrip object When you click on the words Type Here a text box will open up and allow you to type the words that you would like to appear as your first item in the menu Type it as you would like to see it no abbreviations and do not jones employ any VB NET naming conventions here Type the word File and then click Fite in the lower box beneath the word File You ll be given the opportunity to enter an item within the File menu such as Open Save Help and Close Keep your menus as close to the normal menus that users are accustomed to as possible because as we ve already established users hate change When you ve completed the File menu press the Tab key to get to the next menu on the top level of the MenuStrip to enter your next items Here is a form with a completed MenuStrip When Visual Basic NET creates a MenuStrip within a program it will automatically name each of the items you place within it In the example above we have FileToolStripMenultem NewToolStripMenultem and CloseToolStripMenultem Since these name
239. ould act as follows a Using a Select Case on the SelectedIndex of tbMenu i Case 0 display Selected Introduction in lblMessage s text property ii Case 1 display Selected Choice 1 in lblMessage s text property iii Case 2 display Selected Choice 2 in lblMessage s text v Case 3 display Selected Choice 3 in lblMessage s text property mull o v Case 4 display Selected Choice 4 in lblMessage s text property b Then display the name of the selected tab i e it s tb name concatenated alongside the current message in the line below on the label using the following code lblMessage Text lblMessage Text amp vbCrLf amp _ Name of tab amp tbMenu SelectedTab Name amp c Then in the next line of the label display the text that is stored within the selected tab using the following code lblMessage Text lblMessage Text amp vbCrLf amp _ Text on tab amp tbMenu SelectedTab Text amp 9 From the SelectedindexChanged event of tbMenu call the CheckTabs subroutine er ees sea leseseseesSSSSeeS 178 Jane Fletcher South Nottingham College paee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls Lecturer Jane Fletcher Coding for the program Public Class Form2 D
240. ould be disabled Main Drinks menu If the user selects tea then gbExtras should be enabled Put the value Tea into the variable strDrink If the user selects coffee then gbCoffeeType should be enabled Put the value Coffee into the variable strDrink If the user selects milkshake then gbMSFlavour should be enabled Put the value Milkshake into the variable strDrink Once a drink has been selected btnUpdateOrder should be enabled NOTE THE EXTRA SPACE AFTER THE TYPE OF DRINK IN EACH CASE Extras menu If the user chooses to have sugar with their drink then put the value sugar into the variable strSugar If the user chooses to have milk with their drink then put the value milk into the variable StrMilk If the user chooses to have sweetener with their drink then put the value sweetener into the variable strSweetener NOTE THE EXTRA SPACE AFTER THE SELECTED EXTRA IN EACH CASE Coffee Type menu If the user selects latte put Latte into the variable strType The check box for milk should be enabled If the user selects espresso put Espresso into the variable strType The check box for milk should be disabled and unchecked and the variable strMilk should be set to nothing o y 142 Jane Fletcher South Nottingham College p anaa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development
241. ould close the program New should reset the form to its original condition and all variables should be set to their original values The Print option on the menu strip should be disabled 5 When the program loads everything should be visible on the form and the background colour of the menu strip set to whatever is used within the program for the background colour of the form The Print option on the menu strip should be disabled 6 The program needs these variable to be declared at the top of the program strName as string and intNumber as integer 7 At design time PrintDocument1 should be assigned as the Document in the PrintPreviewDialogue control 8 The processing for btnValidate should be as follows a The user s entry into txtName should be validated to be within the length of 1 to 20 characters Anything outside that range should be rejected with an appropriate error message and user should be exited from that procedure b Valid input should be stored in strName c The user s entry into txtNumber should be validated to be a number within the range of 1 to 20 Anything outside that range should be rejected with an appropriate error message and the user exited from that procedure d The message name you are now ready to print should be displayed in lblStatus where name is the value stored in strName 9 The Preview menu strip click event should contain the following code KR WN Start the print pre
242. oupBox2 gbInvoiceAmount Label11 lblDiscountAmount Label12 lblAmountPayable Se 67 Jane Fletcher South Nottingham College pama Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 8 DateTimePickers Lecturer Jane Fletcher A program is needed to meet the following requirements Initial specification A manufacturer of sawn timber sells to a large number of timber yards and DIY shops Assume the user is processing payments from these customers Allow the user to input the date an invoice should have been paid by and the total value of the invoice Calculate how many days late if any the payment has been made If payment has been made 15 or more days before the due date give a 10 discount otherwise give a 5 discount if it has been paid on time Output details about whether payment has been made on time any discount given and the total amount due Overview 1 The program needs these variables declared at the top of the program Dim decInvoiceAmountEntered decInvoiceAmountDue decDiscountGiven As Decimal Dim intDiscountRate intDaysDifference As Integer Dim dtTodaysDate As Date Date Today Dim intDay As Integer dtTodaysDate DayOfWeek Dim dtInvoiceDate As Date Throughout the program use the font of your choice but be consistent When the program loads only the part of the form
243. outine End If If the length of the entry in txtNumber2 0 Then Display a message box saying You must enter a number in the second box Set the cursor focus to txtNumber2 Quit the subroutine End If If the length of the entry in txtNumber2 is gt 3 Then Display a messagebox saying You must enter a number in the range of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine 94 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Lecturer Jane Fletcher End If If the entry in txtNumber2 isn t a number Display a messagebox saying You must enter a number in the range of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine End If Set intNumber2 to hold the value contained in txtNumber2 Check the range entered by comparing intNumber2 with 100 and 1 if it is outside that range then Display a messagebox saying You must enter a number in the range of 1 to 100 in the second box Blank out the text in txtNumber2 Set the cursor focus to txtNumber2 Quit the subroutine End If Check that there is no decimal place contained in txtNumber2 if there is then Display a messagebox saying You must enter an integer in the ra
244. ove shows that the label has a BorderStyle of None The borders of the label are shown with a dotted line the one above also shows that the label is selected notice the grab handles around the edge because otherwise it isn t possible to show where the outline of the label is This label has a BorderStyle of FixedSingle This label has a BorderStyle of Fixed3D Now the label will grow Notice that the text contained in the labels in each of the illustrations above is located in the top left hand corner of the label object While this can be appropriate it doesn t look particularly visually appealing if the purpose of the label is to display some form of output Jane Fletcher South Nottingham College Unit 14 Event Driven Programming SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Commonly used controls Label control edexcel advancing learning changing lives Lecturer Jane Fletcher It is possible to alter the location of the text within the label by use of zm the label s TextAlign property in the Properties Window for that control The default value is TopLeft By clicking on the grid of nine boxes see illustration here you can move the location of where the text of the label will occur The current location is shown as the rere he position of thet button that appears to have been pressed in 1 ext TextAlign UseCompatibleT extRendert T
245. oyee 10 CheckBox2 chkTuesday 20 Button5 btnClose S esSsesSseFEeSEEe 139 Jane Fletcher South Nottingham College pae 66 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Lecturer Jane Fletcher A program is needed to meet the following requirements An integer variable intCounter should be declared at the top of the program When the program loads the entire form should be visible and the cursor placed in txtForename gbDays should be disabled When the user clicks btnProcess the program should validate the entry in txtForename as s having a length between 1 and 12 characters The same validation applies to txtSurname Any illegal input should generate a message box displaying a suitable message the text within the text box should be deleted and the cursor placed into the text box ready for user input Once the number has been validated gbDays should be enabled and If the user checks chkMonday the program should display a concatenated message in the format of into lstHistory Forename Surname works on Monday Do the same for each of the check boxes amending the day as appropriate Add one to a count of days worked intCounter and display this in lblCount in the format shown here This person works intCounter days When the user click
246. plication1 Microsoft Visual Studio _ 218 x File Edit View Project Build Debug Team Data Tools Test Window Help DeGa d saBlale2 o c O S gt uy os ARAM ao lp ij s 5 e no usable controls in this roup Drag an item onto this text o add it to the toolbox Private Sub CheckBox1_CheckedChanged ByVal sender As System Object ByVal e As System EventArgs Handles CheckBox1 CE Form1 vb O m e a w End Sub End Class D ee 6 Jane Fletcher South Nottingham College paee 4 o Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls CheckBox control Lecturer Jane Fletcher Commonly used Properties of the CheckBox control BackColor Sets the background colour of the CheckBox The default background colour is determined by that of the GroupBox in which it sits but it can be changed using the same method as that applied when altering the form s background colour Bear in mind that when you change the BackColor of a CheckBox to be different to that of the GroupBox it belongs to the label associated with the CheckBox is what will change not the actual tick of the check box itself Checked Default value is False meaning that the CheckBox is not selected When the user clicks on a deselected CheckBox its Checked property will change to True and vic
247. pport line on telephone number 0115 9146414 open 8 30am to 5pm Monday to Friday Figure 4 TwoPlusTwo showing your answer Clearing an old set of numbers ready to enter another set When you have finished with the numbers that you have just entered you need to clear them to enable you to enter a new set Click on the black button marked Clear Clear r TwoPlusTwo from SNC PLC The numbers you entered have now gone and the label has cleared Your cursor is now back in the box alongside the prompt First Number ready for you to enter a new set of numbers as shown in Figure 5 First Number Second Number 3 Figure 5 Cleared information ready for new input ao 101 Jane Fletcher South Nottingham College y mnm ON Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives User documentation Lecturer Jane Fletcher Closing TwoPlusTwo When you are ready to close your software you should click once with your mouse ciose on the red button marked Close a Project closing DS When you ve clicked once on the Close button TwoPlusTwo will bid you l Good bye J Goodbye OK Click on the button marked OK and the software will be completely closed TUTORIAL We are going to work through three sums You will be asked
248. pprenticeship Week here a We are hosting an event for schools during Apprenticeship Week 8 10 Feb 2012 click AxisCentre here for details i r m n i EbusSiIness _ Interested in studying with us Object Form 8 Buttons btnHome MenuStript File 9 GroupBoxt ExitToolStripMenultem Exit Button1 btnBack 4 TextBox1 txtWebAddress Button2 btnForward Button6 btnGo Button3 btnStop 3 1 WebBrowser 1 woWebBrowser puran Grane e a 1 2 3 189 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 11 Creating Web Browsers m Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to create a more complex web browser This program also introduces ToolTips 1 In design mode set the Url property of woWebBrowser to www snc ac uk 2 Add a ToolTips control from the ToolBox in design mode Name it ttWebBrowserBits 3 When the program loads the entire form should be visible The web browser itself should stretch across the entire screen regardless of the size of that screen The code for this which should be placed in the form load event is Dim ScreenSize As Size New Size Screen PrimaryScreen Bounds Width _ Screen PrimaryS
249. ptical media drive the Installation Wizard will load and help you to install the software Just follow the on screen prompts by answering Yes and by the time you have finished the process you will have a link to your new software both in your computer s Start menu and also as an icon on your main Windows opening screen as shown here Figure 1 TwoPlusTwo installed Starting your software To start your TwoPlusTwo software double click your mouse in Figure 1 from your main Windows screen When your software starts you will see the main screen as etme shown in Figure 2 What do do if my software doesn t start First of all make sure that it has been installed correctly by following the procedure in the section Installation If not install your software First Number Second Number If this doesn t solve the problem then you should contact the SNC PLC Technical Support line on telephone number 0115 9146414 open 8 30am to 5pm Monday to Friday Clear Process Figure 2 TwoPlusTwo main screen Ka Entering information into TwoPlusTwo When your TwoPlusTwo starts your cursor will be placed next to the prompt First Number Here you need to enter type your first of the two numbers that you want to total What do I enter the number you enter must be a whole number and in the range of 1 to 9999 Next you should press either the Tab key on your
250. quired to write each week based on the ones developed in class It is important that you write each program given to you in the order that they re set since they have been designed with a building block idea in mind if you miss out a brick in your learning wall then you aren t building a very stable foundation and your wall stands an excellent chance of falling down and crushing your feet Or something similar whatever the programming equivalent of a pair of crushed feet is It doesn t matter how many times you attempt to write a program when the author was learning to program sometimes she would have a go at the same program several times until she d learned what she was doing and could repeat it without having to rely on copying or notes as long as when you ve finished and finally move on you understand what you did and why you did it Sometimes students complain that they don t understand programming usually this will happen after maybe the third or fourth lesson and they start looking at the lecturer with dislike and dreading the sessions spent trapped in a classroom with her The lecturer is aware that this happens and expects it At an appropriate point she will launch into her usual speech Imagine that you were learning to speak a foreign language like Klingon for example After four and a half hours three weeks worth of lessons of learning Klingon how fluent do you think you d be You may be able to as
251. r ee ee 8 Jane Fletcher South Nottingham College amame un n Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons Lecturer Jane Fletcher Clear the text box and put the focus up there for the next input txtNumber Text txtNumber Focus End Sub Private Sub Form1_Load ByVal sender As System Object ByVal e As System EventArgs _ Handles MyBase Load Put the focus into the text box txtNumber Focus End Sub Private Sub btnDeleteSelected Click ByVal sender As System Object _ ByVal e As System EventArgs Handles btnDeleteSelected Click The user has chosen to delete the selected item in the list box First check that the user has selected something If lstHistory SelectedIndex 1 Then They haven t so throw them out MsgBox You must pick something to delete first MsgBoxStyle Critical Error Exit Sub End If If we get here then the user has picked something to delete lstHistory Items RemoveAt lstHistory SelectedIndex txtNumber Focus End Sub Private Sub btnDeleteAll Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnDeleteAll Click The user has selected to delete everything Warn them first Dim intResponse As Integer intResponse MsgBox Do you rea
252. r A control structure in its most basic sense is a block of programming code but more specifically they control the flow of logic through the program A program is a set of instructions and Statements that perform certain functions and process information in a set way to provide a set outcome There are three different types of control structure sequence selection and iteration Sequence In programming the word sequence means exactly the same as it does in any other context It means that the instructions or actions or programming statements always occur and always occur in the given order No statement is ever missed out and every statement is always performed When you write program code one line after another with no choices or loops within it it is a sequence The code below is an excerpt from the Click event of btnDisplay and is a simple one written to display a message in a certain format in a label called lblMessage This procedure displays a message to the user in lblMessage Set the text of the label to the message you want to use lblMessage Text Welcome to Visual Basic NET Set the background colour of the label to black lblMessage BackColor Color Black Set the foreground colour of the label to white lblMessage ForeColor Color White Make the label visible now it looks right lb1lMessage Visible True The green text each line prefixed by an apostrophe indicates that this line is a co
253. r IT Practitioners Software Development advancing learning changing lives Commonly used controls PictureBox control Lecturer Jane Fletcher SizeMode of SizeMode of SizeMode of AutoSize Centrelmage and Zoom at design Normal at run time StretchIlmage at time note the lines describing the size that tie run time PictureBox would need to be to accommodate the image The default event of the PictureBox object is the Click event although there are many others available that you could explore It is unusual to assign an event to a PictureBox however generally they are used as a display other than as a dynamic object one that does something or causes an event to happen The Dock property of the PictureBox object allows the designer to decide where the PictureBox should be placed within the form The default value for this property is None There are other options available Top Left Fill Right and Bottom See below to see the effects these different values have on the PictureBox at run time E al Formi EE Cea a Fo E roma CIEE naa rai we CA 36 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls PictureBox control Lecturer Jane Fletcher Co
254. r has entered something with a length in the range of 1 to 20 characters If txtName Text Length Or txtName Text Length gt 20 Then MsgBox Your entry should be text up to 20 characters in length _ MsgBoxStyle Critical ERROR txtName Text txtName Focus Exit Sub End If If we get to here we re valid Add the name to the list box lstName Items Add txtName Text Put the focus back in the cleared text box txtName Text txtName Focus CheckForEntries End Sub Private Sub CheckForEntries This routine checks to make sure that there are some entries in the list box Dim intCount As Integer intCount lstName Items Count If intCount gt Then There are entries so enable all the buttons that apply to the processing of the data in the list box btnRemove Enabled True btnUpdate Enabled True btnClear Enabled True ee F lt lt x aW sOC C C C s i Jane Fletcher South Nottingham College y aae a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Else There are no entries in the list box so disable everything btnRemove Enabled False btnUpdate Enabled False btnClear Enabled False End If End Sub Lecturer Jane Fletcher Private Sub btnUpdate Click se
255. r of the form as a starting point The location is defined using two figures x and y where x is the distance from the left hand margin of the form and y is the distance from the top of the form The default unit of measurement is the pixel one centimetre is approximately 47 pixels Name The default prefix for the Label object is Ibl Ll _ i i i ai _ a i OSOSOSOSOSOOO CT 17 Jane Fletcher South Nottingham College J E LLLE Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Label control Lecturer Jane Fletcher Size Again an x y figure where x is the width of the object and y is the height of the object The unit of measurement is the pixel TabIndex Unless the label is to receive control during run time then the programmer can manually alter the Tablndex to be a high number using the Properties Window at design time See the explanation of the purpose of the Tablndex in the Button object Text The words or numbers that are displayed in the label The label can display anything there is no restriction in terms of what characters can be used since the Text property of a label is classed as a literal TextAlign Text within a label can be displayed using any form of alignment selected by using the TextAlign property in the Properties Window The default value
256. r the first letter of the word strForename StrConv txtForename Text VbStrConv ProperCase b Once this has been accomplished btnProcess should check to ensure that the user has selected a group from lstGroup If not an error message should be displayed via a message box If a group has been selected then it should be stored in strGroup and the SelectedIndex property of lstGroup should be set to c Once input is valid it should be displayed in the list box using the following statement lstStudentsOnTrip Items Add String Format MyFormat _ strForename strSurname strGroup d Both text boxes should be cleared of input and the cursor placed in txtForename to await user input D 07 Jane Fletcher South Nottingham College pae a 6444 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes T Lecturer Jane Fletcher 6 btnDeleteSelected should check to see that the user has selected any line within the list box by examining the list box s SelectedIndex property If nothing has been selected then a message box should be displayed to the user telling them that they must pick a line to delete If a line has been selected then it should be deleted and the cursor put back into txtForename to await user input 7 btnClear should first check to see that
257. rams 12 Creating a Login system Lecturer Jane Fletcher A program is needed to meet the following requirements Overview The purpose of this program is to create the very simplest login screen but this time with the inclusion of a splash screen as well 1 When the program loads the splash screen should be the start up screen Go to the Properties menu of the project then select the last item in that drop down menu the properties of your project and pick the Application tab Make sure that your start up form is set to the splash screen Set the background image of the form to the image of your choice with the proviso that it is an appropriate image and will in no way be offensive to any other person 2 The splash screen should have a timer with an interval set to 1000 The timer should be set to disabled at design time 3 The form load event of the splash screen should enable the timer 4 The timer s tick event the default event for a timer should disable the timer then declare your first form probably Form1 It should then hide itself and show dialog the recently declared form Dim Form1 As Form1 New Form1 Me Hide Form1 ShowDialog 5 When Form1 loads only the top part the form should be visible 6 Throughout the program use the font of your choice 7 Declare two variables at the top of the program Dim intUser As Integer Dim strPassword As String 8 The Close button should close the program
258. re reserved Inbuilt function words Examples include the MsgBox function which allows the programmer to easily code message boxes and StrConv which changes the format of characters Error messages entered by the user to match the requirements of the program e g from a mixture of cases to all upper case Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Quick start to terminology used in this unit f Lecturer Jane Fletcher Processed data An example of the difference between data and information is when a user collects answers to a set of questions in a questionnaire and organises them to put into a computer program That is data When the user has entered this data into the program and processed it it becomes information ou The information that is entered into a program either electronically from a file or a P database or via a user Keyword See Reserved word Information A specific control The terms control and object are interchangeable for the Object purpose of this unit An object is something that can be individually selected and manipulated Output The information generated by the program after processing input Pointer The cursor used at design code time ae The actions to be performed when a particular event is trig
259. re you would like to place the top left hand corner of the GroupBox press the left mouse button to drop the box then keeping the left mouse button pressed drag the GroupBox until it is the size and shape that you need and then release the mouse button zy Li EE 23 A a mi aoe EE gw ka Pi rm a A abl ahi S E Notice that the control has an inbuilt text feature which by default is the name of the GroupBox The default name for the GroupBox control is 6 GroupBox1 followed by GroupBox2 and so on In order to change the text ensure that the GroupBox is the active object and then alter its Text property in the Properties Window Properties vy ax GroupBox1 System Windows Forms Gr a 7 aximumSize 0 a e e e M Enter client information Change Text property ay cy Display after hitting Modifiers Friend r Padding 3 3 3 3 the Retu rn key e RightToLeft No Size 188 54 Tablndex 0 Tag Text Enter client inforr When using a GroupBox it is important to remember that when you re a ee z actually attempting to place other objects within the GroupBox itself you must have selected the GroupBox so that it is the active object You can tell that it is by the fact that grab handles are visible around its edges Incidentally you can use these grab handles to resize the GroupBox in the same way as you can SE r ia with other controls AEA 7 To the right is the GroupBox with two
260. reBox onto a form is to click on the PictureBox icon in the Toolbox shown here and then move across to the form with it When you reach the place where you want the top left hand corner of the PictureBox to be press the left mouse button and drag across and down to i describe the size of PictureBox that you need Release the left mouse button 2 vescrewsn when you re happy BE MonthCalendar NotifyIcon ComboBox DateTimePicker Label LinkLabel ListBox R fe A A Es Once a PictureBox control has been added to a form it is possible to resize it by using the grab handles around the edges which are delimited by dotted lines Notice on the illustration to the right that towards the right corner of peee TE mo the top edge of the PictureBox that there is a small square with an arrow E q within By clicking on this arrow a side menu opens Soe ade ROG from which it is possible to select the image the L Dock in Parent Container E PictureBox is to contain the size mode of the image and whether you wish the image to dock within the parent control In the example here the parent control i e the control in o Se b which the PictureBox is placed is the form F Select Resource a ie Resource context Local resource To insert an image into the PictureBox either use the side menu shown above or click on the ellipses to the right of the Image iee property in the Properties Window The Select
261. rer Jane Fletcher Exercise 3 1 Using Radio Buttons m 7 lbIMessage Welcome to Programming btnDisplay Click one and see what Display message i uf radRed radBlack radWhite radGreen White Ji btnClose C Green Clos C Black A program is needed to meet the following requirements Upon first load lblMessage should not be visible When the user clicks btnDisplay lblMessage should be displayed When the user clicks btnRemove lblMessage should be taken off the screen When the user clicks radRed the background of lblMessage should become red and the text colour should be white When the user clicks radBlack the background of lblMessage should become black and the text colour should be white When the user clicks radWhite the background of lblMessage should become white and the text colour should be black When the user clicks radGreen the background of lblMessage should become green and the text colour should be white When the user clicks btnClose the program should close Complete design documentation is required for this program ee O 3 Jane Fletcher South Nottingham College pma Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Lecturer Jane Fletcher Exercise 3 2 El Mini
262. res E Videos vn uu File name vy All Project Files sIn dsw ve If you can t see your form follow the procedure outlined on page 51 Using File and Open Project on the menu bar Click on File on the menu then move down to Open Project Click on that Navigate your way through the Open Project dialog box until you come to the Solutions file of your project and either double click on that file or click once and then click on Open Again if you can t see your form follow the procedure outlined on page 61 co Microsoft Visual So Si File Edit View Debug Team Data Tools Test Window Help l New Project Ctrl N A A gla wo SCE S Debug ol Fi ase Bes New Web Site Shift Alt N i New Team Project H New File Shift Alt O th Connect to Team Project Open File Close Close Project lL t ssisOOOOOOOSOSOCSS 63 Jane Fletcher South Nottingham College pae Unit 14 Event Driven Programming SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Data types edexcel advancing learning changing lives Lecturer Jane Fletcher A data type is the technical term used within a programming environment for types of information that the programming language is capable of understanding Each different data type has its own characteristics and validation rules Visu
263. rivate Sub CloseToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles CloseToolStripMenuItem Click End the project Me Dispose End End Sub Private Sub btnDone Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnDone Click The user has entered his or her own passcode so check to see if it is valid or not Dim bValid As Boolean bValid False Select Case intUser Case 1 If strPassword 1111 Then 196 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 12 Creating a Login system e Lecturer Jane Fletcher bValid True End If Case 2 If strPassword 2222 Then bValid True End If Case 3 If strPassword 3333 Then bValid True End If Case 4 If strPassword 4444 Then bValid True End If Case 5 If strPassword 5555 Then bValid True End If Case 6 If strPassword 6666 Then bValid True End If End Select If bValid Then Dim form2 As Form2 New Form2 form2 ShowDialog Else MsgBox You have entered an incorrect passcode MsgBoxStyle Critical ERROR End If End Sub Private Sub NewUserToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles NewUserToolStripMenuItem Click Clear everything down
264. rowOnly AutoSizeMode GrowOnly AutoSizeMode GrowOnly AutoValidate EnablePreventFocusChange AutoValidate EnablePreventFocusChange AutoValidate EnablePreventFocusChange Control BackgroundImea Custom Web system BackgroundIma Custom Web System BackgroundIma C activeBorder BackgroundIma C Transparent CancelButton g Black CausesValidatia ContextMenust El DimGray ControlBox BackgroundIma Custom web System Background rng sss ContextMenuSt ControlBox ControlDark Enabled E ControlDarkDark E ControlLight Font C ControlLightLight ForeColor calle SERRE BEEBE EEE Font ForeColor FormBorderSty a e FormBordersty am Red roan E E E a a a i Icon ma Icon 4 Eee ra es cor E ae canal color of the component area EAA a cela color of the component ControlBox If you set this to False then the form will not have the minimise maximise and close buttons on the top blue status bar If you leave it set to True the default value then they remain ne y 10 Jane Fletcher South Nottingham College f lt SS _ P Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Form control Lecturer Jane Fletcher Font The font style settings and size of all text to appear on the form with a default of MS Sans Serif font size 8
265. rpose of the TextBox as a general rule TextBoxes are not used for anything other than gaining information from the user It isn t normal for example to get a user to click on a TextBox when they wish to get the software to perform some sort of processing The way to add a TextBox to a form is to click on the TextBox icon in the Toolbox move across to the Form object and press the left mouse button at the place on the form where the top left hand corner of the TextBox is to be situated Drag across to describe the width of the TextBox that you want Note that Big you can t actually alter the height of the TextBox at this Stage since by default TextBoxes don t allow a multiline user entry and the height of the box is determined by its Font property The image to the right shows an active TextBox that has been placed in a GroupBox and alongside a Label used as a prompt to the user to show in this case that the TextBox is to be used for inputting information on the client s forename Forename Surname The default event of a TextBox object is the TextChanged event The TextChanged event is triggered every time the program detects that there has been some form of change to the TextBox this occurs every time there is a change in other words for every character typed into the TextBox by the user In view of the fact that it isn t usual for the developer to want to check one character at a time what the user has entered into a Text
266. rs added together which is to be displayed in the label for that purpose intTotal Processes Click Event for btnProcess If txtFirstNumber s text length 0 Then Display message to the user stating that an error has occurred Put the focus of the cursor into txtFirstNumber Exit the subroutine End If If txtFirstNumber s text length gt 4 Then Display message to the user stating that an error has occurred Remove the text from txtFirstNumber Put the focus of the cursor into txtFirstNumber Exit the subroutine End If If txtFirstNumber s text is not numeric Display message to the user stating that an error has occurred Remove the text from txtFirstNumber Put the focus of the cursor into txtFirstNumber Exit the subroutine End If Store the value in the Text property of txtFirstNumber in intFirstNumber If intFirstNumber lt 1 or intFirstNumber gt 9999 Display message to the user stating that an error has occurred Remove the text from txtFirstNumber Put the focus of the cursor into txtFirstNumber Exit the subroutine End If If txtSecondNumber s text length 0 Then Display message to the user stating that an error has occurred Put the focus of the cursor into txtSecondNumber O O O O 85 Jane Fletcher South Nottingham College p manaa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Design document
267. rticular item in an array for example so you will use For Each e You want to repeat a loop while a certain condition remains true so you will use Do While Loop or Do Loop While e You want to repeat a loop until a certain condition becomes true so you will use Do Until Loop For Next This loop will perform a set of instructions which are contained within the For Next Statements a set number of times determined by the starting values and ending values which are specified either directly or within variables With this type of loop you do not have to worry about incrementing any counters because Visual Basic NET does this for you The example below will take two values from the user one to determine the number to be multiplied and the other to determine how many times that number will be multiplied thus generating a times table for that number This process will take the user s inputs from txtInput and txtMultiplier and will use the value in txtInput to determine how many times the loop is to be performed and the value in txtMultiplier is used as the figure that will be multiplied For example the 12 times table will be generated 10 times if the user enters 10 into txtInput and 12 in txtMultiplier Dim intCounter As Integer The variable used as a counter within the loop Dim intMultiplier As Integer The number the user wants to multiply Dim intAnswer As Integer The result of the calculat
268. ryDateTimePicker 26 11 2011 09 48 Microsoft Visual 1 KE This folder contains a further folder and a Microsoft Visual Studio Solution file called prjDateTmePicker It is always this Solution file that should be opened when a previously created project is opened this is the front door to the project and gives the NET framework access to all the different files created as part of the original and edited project If you are accessing a previously written project via Windows Explorer NEVER open the project by clicking lll KF t SSsSsSsSSS e 52 Jane Fletcher South Nottingham College anmam _ 0 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Creating a folder structure Lecturer Jane Fletcher on any other file within the project because doing so stands an excellent chance of corrupting your work Let us assume that you are on Week One of the course and need to start creating your file structure 1 Within your My Documents folder create a new folder entitled Unit 14 Event Driven Programming 2 Within this folder create a folder called Weekly Programs 3 Within this folder create a folder called Week 01 Note the zero before the 1 which will ensure that week two s folder comes before week 11 s folder 4 Now create a
269. s Wt 13 Week 13 programming exercise one 29 11 2011 12 40 Microsoft Word D 209 KB a Music T 13 Week 13 programming exercise one 29 11 2011 13 21 Adobe Acrobat D 143 KB Pictures Wh 13 Week 13 programming exercise two 29 11 2011 15 24 Microsoft Word D 240 KB BE Videos TH 13 Week 13 programming exercise two 29 11 2011 13 22 Adobe Acrobat D 160 KB Notice the top three folders contained in the subfolder Exercise done in class Exercise One and Exercise Two These folders were created by the author to separate the three different programs to be written during week 13 Next we will open the folder Exercise done in class shown below G L Weekly programs Week 13 CBeercise done in class gt gt z Organize v Share with Burn New folder zz 00 4 g jate modifiec ype Size gt Favorites Name Date modified Type ize ME Desktop d prjDateTimePicker 16 05 2012 08 26 File folder Pi Downloads Folder Exercise done in class contains a sub folder called prjDateTimePicker created by the Visual Basic NET environment This was not created by the author _ LL EBL MMM GQ di Weekl3 Exercise done in clas Organize Share with Burn New folder fil a Warr j neliti wo Iz i 43 Favorites Name Date modified Type Size ME Desktop di pryDateTimePicker 16 05 2012 08 26 File folder p Downloads S Berent Blarer p
270. s EZE Total This Sale This sale a a a ers ey 3 NewToolStripMenultem 4 Closefootsrpwenutem GroupBox1 Label1 Blu ray Label2 Price 8 Label3 Ordered Zs Label4 Remove advancing learning changing lives Lecturer Jane Fletcher ListBox1 lstTitle ListBox2 lstPrice ListBox3 lstOrdered ListBox4 EE Ca a roo s D Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Lecturer Jane Fletcher A program is needed to meet the following requirements This program practices the art of synchronising list box pointers 1 The program needs the following variables to be declared at the top of the program Dim decTotal As Decimal Used to add up the total of how much the customer owes Dim decPrice As Decimal Dim intQuantity As Integer Dim MyFormat As String 40 1 5 2 5 3 6 Title Price Quantity Total The menu strip should have one item at the top level File File should contain two items New and Close Close should close the program New should reset the form to its original condition and all variables should be set to their original values lstOrdered should have all its values set back to 0 JAUN Dim intPointer
271. s are clear and readily understood there is no need to change the defaults It is possible to change the direction of the text within the MenuStrip by altering the TextDirection property and for the items within the menu to be shown right aligned by altering the RightToLeft property to Yes To change the colours used within the MenuStrip object change the BackColor as usual in the Properties window to each individual item in the sub menus as well as at the top level However ForeColor will have to be altered in the code like this MenuStrip1 ForeColor Color Red However this will only alter the TOP layer of the MenuStrip so any lower levels like New and Close in our example will have to be altered individually NewToolStripMenuItem ForeColor Color Red CloseToolStripMenuItem ForeColor Color Red O t lt ai i s s S OSS SO 30 Jane Fletcher South Nottingham College pae Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls MenuStrip control Lecturer Jane Fletcher Once you have a MenuStrip object on your form it is extremely easy to make it work all you have to do is within the design view double click on the lowest level of the menu to see the code view for that object s Click event which is the default event of the MenuStrip The
272. s being numeric and in the range of 1 to 9999 Any invalid entry should be reported to the user via a message box invalid input should be removed and the cursor set into the text box ready for further user entry 11 Valid user entry should be stored in the variable intNumber 12 Each number that is entered by the user should be processed as follows a If the value in intNumber is less than the value in intlowest then store the value of intNumber into the variable intLowest and display this number in lblLowest b If the value in intNumber is greater than the value in intHighest then store the value of intNumber into the variable intHighest and display this number in lblHighest c intTotal should be added to the value in variable intTotal and that value displayed in the label lblTotal d One should be added to the variable intCount e decAverage should be calculated by dividing intTotal by intCount and this value Stored in decAverage 13 The text box txtNumber should be cleared and the cursor replaced there to wait for user input after this processing has occurred OH S ese 56 Jane Fletcher South Nottingham College SS Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 7 Number processing with variables Lecturer Jane Fletcher Coding for this project Public Class Form1 Dim intNum
273. s btnDeleteSelected the program must make sure that the user has actually selected something in lstHistory If they have then that entry should be deleted One should be removed from the variable intCounter and the new total of days worked updated in blCount When the user clicks btnDeleteAll the program must ask the user if they are sure that they wish to delete the entire contents of the list box via a message box If the user answers yes then the contents of the list box must be deleted the contents of the text box deleted and the cursor placed in the box ready for user entry lblCount should be cleared and the variable intCounter set to equal 0 When the user clicks btnEnterAnotherEmployee gbDays should be disabled and the text in both text boxes should be cleared lblCount should be cleared and the variable intCounter set to equal 0 All the check boxes should be unchecked and the cursor put in txtForename When the user clicks btnClose the entire program should end CCG 14 0 Jane Fletcher South Nottingham College p lt Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Lecturer Jane Fletcher Exercise 5 2 Using Check Boxes MENU Your order Coffee type C Latte Extras Shake taste Ea M Sugar C Banana g I Milk C Strawberry Swee
274. s listbox see 1 in the illustration above and pull down the list of events in the Events listbox see 2 in the illustration above Ye Jane Fletcher South Nottingham College l O Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Button control Lecturer Jane Fletcher Commonly used properties for the Button control Name The Name property is what you want to call the button within the program If you wish to change the Name property the prefix of the button name should always be btn lower case followed by a descriptive name with the first letter of the first and subsequent words being in upper case with the rest of the letters in lower case Example names would be btnDisplayLabel btnProcessInput and so on BackColor The colour of the background of the button Unless you change this property the button will have the default background colour the same as that of the Form object upon which it sits It is possible to change this property at design time as well as within the program s code See the Form control for a deeper explanation as to how to change the BackColor property Enabled This property defaults to True which means that the button is useable within the form If the property is set to False then the button will appear greyed out on the form at run
275. s so be aware If you want to save changes made to your project click on the Yes button If you clicked Close by accident click on the Cancel button and you will be taken back to the Save changes to the following items prj WeekOneProgramDonelnClass Form1 resx Form1 Designer vb Form1 vb NET environment to the place you were at before you clicked on Close To close a project without closing VB NET go to File in the menu bar and click Close Project o0 pr WeekOneProgramDonelnClass Microsoft Visual Studio File Edit View Project Build Debug Team Data Format Tools Test Window Help l New Project Ctrl N e f Glp wae Debug E Ke a cA oe 3 1 New Web Site Shift Alt N i ih New Team Project New File Open Project Ctrl O0 Open Web Site Shift Alt O Connect to Team Project Open File Add r la Save Formi vb Ctrl S Save Form1 vb As Save All Ctrl Shift S Export Template Source Control d Recent Files r Recent Projects and Solutions gt Exit Tooltip TreeView Column a WebBrowser 4 Containers GroupBox E Panel o Solution Explorer alleen E3 prjWeekOneProgramDonelnClass a My Project EE Form1 vb S Solution Explorer f pAs Properties Form1 System Windows Forms Form B2 41 al gt MaximumSize MinimizeBox gt MinimumSiz
276. sage lbl essage pieten Efa BorderStyle FixedSingle nd Sub rivate Sub RedioButton1_CheckedChanged Byvel sender As System Object ByVel e As System EventArgs Handles RadioSutton1 CheckedChenged of ti redio oe is to alter the style of the border of the message Iebessnge torderat Bor tyle Fi 23D Private Sub btnClose_Click Byvel sender As System Object SyVel e As System Ewentargs Handles This button closes the project Sub redvisible_CheckedChanged SyVvel sender As System Object ByVal e As System Ewent rgs Handles redvisible checkedChanged a ee i the label without altering the visible property Peia age w message is now displayed Sete gt ell the style enhancing group boxe End S Private Sub redNotVisible CheckedChanged Syvel sender As System Object ByVal e As System EventArgs Handles redNotVisible CheckedChanged To remove a sage from the label without hiding the label lbl essage Disablescutt ois able all the style enhancing group boxes End Sub Sub redTopLeft_CheckedChanged Syval sender As System Object ByVal e As System EventArgs ndles radTopLeft CheckedcChanged alter Sherali t anegia 1blessage Tertatigr liga Key 1 Code window In order to access the code window to write the code for a specific object just double click on the object itself in the design view s editing panel item 4 on the previous page There are other ways of accessing the code window but as an introduction th
277. ser clicks btnDisplay lblMessage should be displayed by altering the Visible property of lblMessage to be True in the Click event of btnDisplay When the user clicks btnRemove lblMessage should be taken off the screen by altering the Visible property of lblMessage to be False in the Click event of btnRemove When the user clicks btnClose the program should close Use the key word End in the click event of btnClose Don t forget to comment your program Now experiment Try making the label a different colour Try altering the font of the objects Add other messages remember though be polite o A 112 Jane Fletcher South Nottingham College a mnm ON Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 1 Using Labels and Buttons p aa Lecturer Jane Fletcher Coding for the program Public Class Form1 Private Sub btnClose Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnClose Click Stop the project running End End Sub Private Sub btnDisplay Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnDisplay Click Display the label by altering the Visible property lb1lMessage Visible True End Sub Private Sub btnRemove Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnRemove Click
278. sh to change the Name property the prefix of the form name should always be frm lower case followed by a descriptive name with the first letter of the first and subsequent words being in upper case with the rest of the letters in lower case Example names would be frmSplashScreen frmLoginScreen and so on AcceptButton The AcceptButton is the name of the control object usually a button whose code will be executed if the user presses the Enter or Return key when the software is running BackColor The colour of the background of the form This will also determine the default background colour of all objects that are placed on the form with exceptions If you wish to change the background colour of an object on the form you must alter the BackColor property of that object individually To change a background colour click on the downward arrow to the right of the BackColor property in the Properties Window From here there are several ways of changing the background colour The first is to select a colour from the System palette displayed as default shown in the first image below A wider choice is available by clicking on the Web tab as shown in the second image below A further choice is available on the Custom tab shown in the third image below Formi System Windows Forms Form Formi System Windows Forms Form Formi System Windows Forms Form MA saia F wa AutoSize False AutoSize False I AutoSize False AutoSizeMode G
279. should have been done before you complete the task in hand For example if you want to wash your hands you will need to have found a water source before you can do that e Tell the user what to do if an error occurs Preferably your user instructions should have a section all about what error messages they can expect to see and under what conditions e Put any warnings in a place where they are clearly visible and obvious e Tell the user what they ought to be doing next when this particular task is completed e Write using language that is appropriate for your user O O O SS 98 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives User documentation Lecturer Jane Fletcher Sometimes it is necessary to put the user instructions in context by giving an overview of where this particular piece of software will fit within the business If this helps your users to understand they whys and wherefores of your software then it is a worthwhile task for you to do When you are writing your user instructions it is important to take into account your audience remember that they might be used by more than one level of user For example your software might be used by people whose only job is to input information into your system they want a quick start easy to read set of instructions
280. splay the name of the website being found in the Text property of the form Me Text Finding amp strWebAddress Fee 91 Jane Fletcher South Nottingham College a aaee N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 11 Creating Web Browsers Lecturer Jane Fletcher Extension activities 1 Add a combo box to search using Google wbobWebBrowser Navigate http www google co uk searchPhl en amp g _ txtSearch Text 2 Change the AcceptButton of the form to be context specific as per the example program called WebBrowserWithExtensionActivities found on the S drive in folder Week 20 for this unit ee F igs 92 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 12 Creating a Login system Lecturer Jane Fletcher 12 0 Specification for program developed in class Making a login screen File File New User Which user are you Enter your pass code ongratulations File Congratulations You are logged in 2 Menustript File 3___NewilserToolstripMenulter New User 4 __CloseToolStripMenuitem Close 5 Groupboxt ooo oa oa
281. ss Form1 Dim intNumber As Integer Private Sub btnClose Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnClose Click Close the project End End Sub Private Sub btnProcess Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnProcess Click Get the input from the user and validate it The input must be numeric and in the range of 1 to 100 If txtNumber Text Length Then the user hasn t entered anything MsgBox You haven t entered anything MsgBoxStyle Critical Error txtNumber Focus Exit Sub End If If txtNumber Text Length gt 3 Then the user has entered too much MsgBox Your entry is too long MsgBoxStyle Critical Error txtNumber Text txtNumber Focus Exit Sub End If If Not IsNumeric txtNumber Text Then the entry isn t a number MsgBox You haven t entered a number MsgBoxStyle Critical Error txtNumber Text txtNumber Focus Exit Sub End If The user has entered a number so store it in an integer variable intNumber txtNumber Text If intNumber lt 1 Or intNumber gt 100 Then The user s entry is numeric but outside the valid range MsgBox You have entered a number outside the range of 1 to 100 _ MsgBoxStyle Critical Error txtNumber Text txtNumber Focus Exit Sub End If By the time we get to here the entry is valid so we can add it to the history list box lstHistory Items Add intNumbe
282. stem EventArgs _ Handles NewToolStripMenuItem Click lb1lStatus Text txtName Text txtName Focus PrintToolStripMenuItem Enabled False End Sub End Class C a Jane Fletcher South Nottingham College pae 4 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing Lecturer Jane Fletcher Exercise 14 1 Using PrintDocument Enter information e Name EE Number Using PrintDoc umant File Print 5 Preview 6 Enter information Name Jane Validate Number 20 Jane you are now ready to print 9 label TextBoxt bxtName oseToolStr ate Validate 15 i 1 2 3 5 reviewToolStripMenultem Hidden PrintPreviewDialog GroupBox1 1500 Hidden PrintDocument1 7 Babel 5 2 i C 7 OY esi SNS 215 Jane Fletcher South Nottingham College pae U Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing j _ S _ _ _ _ ____ _ Lecturer Jane Fletcher A program is needed to meet the following requirements The menu strip should have two items at the top level File and Print File should contain two items New and Close Close sh
283. strAddress End Sub Private Sub Form1_Load ByVal sender As System Object ByVal e As System EventArgs _ Handles MyBase Load Dim ScreenSize As Size New Size Screen PrimaryScreen Bounds Width _ Screen PrimaryScreen Bounds Height Dim intWidth intHeight As Integer intWidth Screen PrimaryScreen Bounds Width intHeight Screen PrimaryScreen Bounds Height wbWebBrowser Left 20 wbWebBrowser Width intWidth 40 wbWebBrowser Height intHeight 150 End Sub Private Sub BackToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles BackToolStripMenuItem Click wbWebBrowser GoBack End Sub ee s sO ee 87 Jane Fletcher South Nottingham College pame N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 11 Creating Web Browsers m Lecturer Jane Fletcher Private Sub ForwardToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles ForwardToolStripMenuItem Click wbWebBrowser GoForward End Sub Private Sub ExitToolStripMenuItem Click sender As System Object e As System EventArgs _ Handles ExitToolStripMenuItem Click End End Sub End Class ee i _ i isOsS SC C C 88 Jane Fletcher South Nottingham College paee 6 a BEE e Dri ean Unit 14 Event Dri
284. swers yes then the contents of the list box must be deleted the contents of the text box deleted and the cursor placed in the box ready for user entry When the user clicks btnEnterAnotherEmployee gbDays should be disabled and the text in both text boxes should be cleared All the check boxes should be unchecked and the cursor put in txtForename When the user clicks btnClose the entire program should end if 135 Jane Fletcher South Nottingham College p SS Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Lecturer Jane Fletcher Coding for the program Public Class Form1 Private Sub btnClose Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnClose Click End the project End End Sub Private Sub btnProcess Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnProcess Click Validate the user s entry into the two text boxes to make sure that they have entered something and that that entry isn t too long If txtForename Text Length Then MsgBox You must enter a forename MsgBoxStyle Critical ERROR txtForename Focus Exit Sub End If If txtForename Text Length gt 12 Then MsgBox You are allowed up to 12 characters for a forename MsgBoxStyle Critical ERROR txtForename
285. t o o fom CB Butor btnProcess 2 MenuStrip ee 9 Button2 btnUpdate 3 NewToolStripMenultem Button3 btnRemove CloseToolStripMenultem Button4 btnClear gt GroupBox1 gbAdd GroupBox2 gbUpdate 6 TextBox1 txtName txtName 1 13000 TextBox2 TextBox2 txtUpdatedName to ara ton oon Button5 btnDone 217 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox lt lt SS Lecturer Jane Fletcher A program is needed to meet the following requirements This program introduces how to insert data into list boxes 1 The program needs the following variable to be declared at the top of the program Dim intPointer As Integer The menu strip should have one item at the top level File File should contain two items New and Close Close should close the program New should reset the form to its original condition and all variables should be set to their original values The subroutine CheckForEntries should be performed See item 7 in this specification 6 When the program loads everything except gbUpdate should be visible on the form and the background colour of the menu strip set to whatever is used within the program for the background colour of the f
286. tTabRect e Index Dim FillBrush As New SolidBrush Color Black Dim TextBrush As New SolidBrush Color White Dim sf As New StringFormat sf Alignment StringAlignment Center sf LineAlignment StringAlignment Center If we are currently painting the Selected TabItem we ll change the brush colors and inflate the rectangle If CBool e State And DrawitemState Selected Then FillBrush Color Color wWhite TextBrush Color Color Black ItemRect Inflate 2 2 End If Next we ll paint the TabItem with our Fill Brush e Graphics FillRectangle FillBrush ItemRect Now draw the text e Graphics DrawString CurrentTab Text e Font TextBrush RectangleF op Implicit ItemRect sf Reset any Graphics rotation e Graphics ResetTransform ene Jane Fletcher South Nottingham College paee ON Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls lt lt lt lt lt lt _ Lecturer Jane Fletcher Finally we should Dispose of our brushes FillBrush Dispose TextBrush Dispose 7 Upon form load the foreground colour of the menu should match that of the form The introduction tab should be selected using the Selectedindex property of tbMenu and setting it to 0 The form load procedure should then call the subroutine CheckTabs 8 The CheckTabs subroutine sh
287. te form of Appendix 2 of this document It will help you to get to grips with some of the different uses of common words when you re a programmer words have different meanings to the ones you re used to For example a form when you re not a programmer could be either a wooden bench that you have to sit on when you re in a school gym or something you have to fill in when you re applying for credit or for a college course When you re a programmer a form is an object that is the screen that the user sees when the software is running As a quick start guide here is a very brief run down of some of the most popular terms used within this unit Term Definition este The words that make up the program The code must follow the correct syntax or the compiler will throw up error messages The section of the program editor that allows the programmer to write the processes Code view for the events belonging to the objects on a form When the program code written in language understandable to humans is converted to language understandable by the computer Control A specific visual object that the programmer places on a form usually at design time Crach The term used within the world of IT meaning an abrupt and unscheduled end to a program s execution due to an unforeseen error Compile Collections of information usually on a related subject that have been formatted in a specific way Data is unprocessed information
288. ten as gt Less than is written as lt What happens if you input 0 in txtSecondNumber and then click the Divide radio button Whoops Remember to internally document your code OS C lt OSOSNSCSCS Ssts i a Se 5 Jane Fletcher South Nottingham College p Sa Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 4 Introducing ListBoxes and RadioButtons Lecturer Jane Fletcher 4 0 Specification for program developed in class Enter a number 1 100 alje Delete Selected Delete All History Close a 1 Form GroupBox1 a TextBox1 txtNumber Button1 btnProcess GroupBox2 o ListBox1 lstHistory Button2 btnDeleteSelected Button3 btnDeleteAll 9 Button4 btnClose A program is needed to meet the following requirements When the program loads the entire form should be visible and the cursor placed in txtNumber When the user clicks btnProcess the program should validate the entry in txtNumber as being numeric and within the range of 1 to 100 Any illegal input should generate a message box displaying a suitable message the text within the text box should be deleted and the cursor placed into the text box ready for user input ee ee 6 Jane Fletcher South Nottingham College oS Sa
289. tener C Chocolate Clear Selected 22 EILG 2 Close Clear All Item Object CheckBox4 chkLatte CheckBox5 chkEspresso CheckBox6 chkCappucino GroupBox5 gbMSFlavour RadioButton4 radBanana RadioButton6 radChocolate Button1 btnUpdateorder ListBox1 lstYourOrder Button2 btnClearAll Button3 btnClearSelected Button4 btnClose GroupBox3 gbExtras CheckBox1 chkSugar CheckBox2 chkMilk CheckBox3 chkSweetener roupBox4 gbCoffeeT ype RadioButton3 radMilkShake WF RadioButton5 radStrawberry 12 13 14 15 16 17 18 19 20 21 22 3 n 141 Jane Fletcher South Nottingham College 2_ _ S SS Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 5 Introducing CheckBoxes Lecturer Jane Fletcher A program is needed to meet the following requirements General String variables strDrink strT ype strSugar strMilk strOrder and strSweetner should be declared at the top of the program When the program loads all group boxes except GroupBox1 and GroupBox2 should be disabled Note that neither of these are referred to within the code and therefore do not have to have a name other than the default allocated by Visual Basic NET Once the user has selected a choice of beverage other group boxes will become available as appropriate btnUpdateOrder sh
290. text box Exit Sub Quit this procedure because user entry is invalid and we can t proceed End If Dim decPrice As Decimal This is the variable to hold the input from the text box decPrice txtInput Text Assign the value from the text box into the numeric decimal variable Check that the information in the variable is within the range of 99p to 99 99 If decPrice lt 99 Or decPrice gt 99 99 Then MsgBox You must enter a price in the range of 99p to 99 99 _ MsgBoxStyle Critical INPUT OUT OF RANGE txtInput Text Erase invalid text from the text box txtInput Focus Put the cursor back into the text box Exit Sub Quit this procedure because user entry is invalid and we can t proceed End If End Sub Notice that the user isn t supposed to enter either a p for pence or a pound sign This would make the input be classed as text rather than numeric If you are validating the contents of a TextBox object for non numeric input then you would just need to use the first two checks for length being 0 meaning that the user hasn t entered anything and length being greater than a set number of characters There are many more complicated ways of validation which you could use but are for you to research and try out rather than for the author to explain here OOS e 9 Jane Fletcher South Nottingham College p aeaee Unit 14 Event Driven Programming edexcel SouthNottingha
291. that will enable them to start work straight away It also might be used by the company accountant he or she will need a much more detailed set of information as to how the information output from the system is calculated and where it is likely to go after it has been processed It might also be used by somebody who is manning a help desk users who are having issues with the software might ring the help desk for support so help desk operators are going to need a very in depth analysis of the software in front of them There might be a case for these users having access to the technical documentation as well as the user documentation of course Given this it might be a plan to divide your user instructions into sections that are aimed at different users if the software warrants it it might even mean that different user manuals are necessary one for each type of user Key points to take into consideration when you are writing your instructions e f a picture is necessary then include one but not at the expense of explaining in words what the user is to do e Keep your language clear concise and unambiguous If it is necessary to include a number give the range of the numbers that are valid for example e Don t use flowery and over descriptive language e Make sure that your instructions are readily navigated your users don t want to have to read through 10 pages of irrelevant waffle before they find the information they nee
292. the corresponding value in lstOrdered Get how many we had ordered of this blu ray in the first instance Dim intQuantity As Integer intQuantity lstOrdered Items Item intPointer intQuantity now contains the value of how many of that title have been ordered already c After that the program must check to see that the selected title has an order placed already and if not display an appropriate error message If an order is in existence then one must be deducted from the quantity ordered and the list box for Orders updated check to make sure that there is something there to remove If intQuantity gt Then Remove the old amount of blu rays lstOrdered Items RemoveAt lstRemove SelectedIndex intQuantity 1 a 226 Jane Fletcher South Nottingham College aaae a 0 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Insert the updated number of blu rays lstOrdered Items Insert intPointer intQuantity Else MsgBox There are no orders for this item MsgBoxStyle Critical ERROR End If Lecturer Jane Fletcher 12 On the click event of btnTotal a Clear any current contents of lstSale b Set the variable decTotal to equal 0 c For each title the number of orders should be examined and if that number is greater than O
293. the program editor that contains all the controls that can be put onto a form l What decrees which event handler will be run for example clicking a mouse on a Trigger function i button will cause the associated event handler to run the code written for that event ear The person or team of persons who will be using the program when it is eventually handed over Written document online or paper based aimed at the user i e not an IT User documentation professional telling them how to install use deinstall the system program in question The form where the user works with the program usually putting data in or gettin User interface prog yP 6 6 6 data out Variable An area of electronic storage that has a name and type as defined by the programmer and will hold data at some point during program execution Ll st i i s SOOO 5 Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Visual Studio Editor Lecturer Jane Fletcher Design View Key Menu bar Menu icons can be customised Toolbox containing objects in design view Editing panel for active form Minimise Maximise Close buttons for the software Solution Explorer Properties Window default to Alphabetical as the display method see arrow 8 Ou
294. then the number of copies of that particular title should be multiplied by the corresponding price in lstPrice and the total for that sum stored in a very local variable decNetPrice decNetPrice should be added to decTotal The appropriate item should be displayed in the list box lstSale using MyFormat title followed by price followed by quantity ordered followed by net price Examine each of the objects and if there are any orders for this object process it For intPointer To lstTitle Items Count 1 Check to see if the user has ordered any of these blu rays by examining the value stored in the Ordered column If lstOrdered Items Item intPointer gt Then Save the price of this blu ray for use in mathematical calculation decPrice lstPrice Items Item intPointer Get how many orders we d already got for this item intQuantity lstOrdered Items Item intPointer Calculate how much the sale is worth for the list box Dim decNetPrice As Decimal decPrice intQuantity Display the total transaction for the list box lstSale Items Add String Format MyFormat _ lstTitle Items Item intPointer _ Format decPrice Currency _ intQuantity Format decNetPrice Currency Accumulate the overall total for the label when the user clicks total button decTotal decNetPrice End If Next intPointer d Display decTotal in currency format in lblAmountOwing e Ensure that no item in lstSale is se
295. time and the user will not be able to click on it It is possible to change this property at design time as well as within the program s code Font Determines the size style and type of font to be used in the Text property of the button Clicking on the ellipses to the right of the Font property in the Properties Window generates the Font Dialog Box which allows the developer to select his or her choice of font style size ForeColor The colour of the text within the button Unless you change this property the button will have the default foreground colour similar to the Form object Location Where the object will appear on the form using the top left hand corner of the form as a starting point The location is defined using two figures x and y where x is the distance from the left hand margin of the form and y is the distance from the top of the form The default unit of measurement is the pixel one centimetre is approximately 47 pixels Name The default prefix for a Button control is btn Size Again an x y figure where x is the width of the object and y is the height of the object The unit of measurement is the pixel ey 0 C a 3 Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls Button control o Lecturer Ja
296. tion error messages specialist software tools eg debug Review against specifications requirements interim reviews Documentation user technical Assessment and grading criteria In order to pass this unit the evidence that the learner presents for assessment needs to demonstrate that they can meet all the learning outcomes for the unit The assessment criteria for a pass grade describe the level of achievement required to pass this unit To achieve a pass grade the To achieve a merit grade the To achieve a distinction grade evidence must show that the evidence must show that in the evidence must show that learner is able to addition to the pass criteria in addition to the pass and the learner is able to merit criteria the learner is able to discuss how an operating evaluate the suitability of system can be viewed as an event driven programs for event driven application non graphical applications give reasons for the tools and techniques used in the production of an event driven application design an event driven application to meet defined requirements implement a working event driven application to meet defined requirements test an event driven analyse actual test results application against expected results to identify discrepancies create onscreen help to create technical assist the users of a documentation for the computer program Support and maintenance of a computer program Jane Fletcher South Nottingham Col
297. to enter some information into TwoPlusTwo and some of it will look incorrect however it is important that you have some experience of mistakes so that when you are using the software properly you will have seen the error messages that TwoPlusTwo will give you and you will know what to do and how to put the problem right Lesson 1 Entering information into First Number Nothing entered into First Number at all Load TwoPlusTwo and at the prompt First Number don t enter anything before you click the Process button TwoPlusT wo will generate an error message No input in first number x You must enter a number in the range of 1 to 9999 Look at the top line of this error message it says No input in first number in the top line of this message and You must enter a number in the range of 1 to 9999 as the main message Click the button that says OK and you will be back to the main screen of TwoPlusTwoO You entered something that is too long Now enter 11111111 into the box alongside the prompt First Number and click the Process button Input in first number is too long Es X You must enter a number in the range of 1 to 9999 eee ee 02 Jane Fletcher South Nottingham College oS SS aS 0 e Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning chang
298. to give learners a generic event driven program The documentation must be coherent and laid out according to the standards that learners have been taught previously In order to gain a distinction grade learners must achieve all of the pass and merit criteria and both the distinction criteria For D1 learners will evaluate the suitability of event driven programs for non graphical applications Evidence for this criterion should be a short report or similarly detailed presentation For D2 learners will evaluate an event driven application There is the option here for the learner to review their P5 work or to be given a generic program to review Alternatively the tutor could give learners the work of one of their peers to review Evidence should be a short report or similarly detailed presentation Indicative reading for learners Textbooks Balena F Programming Microsoft Visual Basic 6 Microsoft Press US 1999 ISBN 10 0735605580 ISBN 13 978 0735605589 Bond M Law D Longshaw A Haywood D and Roxburgh P Sams Teach Yourself J2EE in 21 Days 2nd Edition Sams 2004 ISBN 10 0672325586 ISBN 13 978 0672325588 Palmer G Java Event Handling Prentice Hall 2001 ISBN 10 0130418021 ISBN 13 978 0130418029 Longshaw J and Sharp J Visual J NET Core Reference Microsoft Press US 2002 ISBN 10 0735615500 ISBN 13 978 0735615502 Suddeth J Programming with Visual Studio NET 2005 Lulu com 2006 ISBN 10 1411664477 ISBN 13 978
299. tput or Debug window NO OF KR WN The illustration above is the usual layout of the Visual Basic Editor Individual developers can tailor the Editor to meet their own needs but when you start out as a programmer it is best to stick to the layout above If you lose one of the windows try going to View on the menu bar item 1 above and click on the missing window s name there If you find that the new window that you ve just found opens up in the wrong place right click on the blue bar at the top of that window and click Dock ef 6 Jane Fletcher South Nottingham College l Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Visual Studio Editor L Lecturer Jane Fletcher Source Code View Prooram name Microsoft Visual Sthariin w E a File Edit View Project ete Public Class Form1 Din strFontStyle As String im intFontSize As Integer Private Sub redWone_CheckedChanged ByVel sender As System Object ByVal e As System EventArgs Handles redtione CheckedChanged The pi e oft redio Se is to alter the style of the border of the message Ihlen elan paira BorderStyle None nd Sub Sub redFixedSingle_CheckedChanged 8yval sender As System Object ByVal e As System EventArgs Handles redFixedSingle Checkedchanged The purpose of this radio aa is to alter the style of the border of the mes
300. txtUpdatedName Text lstName SelectedItem txtUpdatedName Focus b Assuming correct input the program should now remove the old entry from lstName and replace it with the new entry from txtUpdatedName but in the same place as the old name using intPointer to indicate where in the list box the entry should be positioned Remove the old item lstName Items RemoveAt 1lstName SelectedIndex Put the new item in the old one s place lstName Items Insert intPointer txtUpdatedName Text The accept button of the form should be set to btnProcess Set gbUpdate to be invisible Set gbAdd to be visible Put the cursor in txtName to await user entry MaN 11 On the Click event of btnRemove in this order a Check to ensure that the user has selected a name in lstName by examining the Selectedindex property of lstName to ensure that it isn t equal to 1 If it is then a message box should be shown with a suitable error message and the subroutine exited b Assuming that an entry has been selected remove it OY eses s SOSOSONSNNNNNNNesSSSe 219 Jane Fletcher South Nottingham College aaae Unit 14 Event Driven Programming edexcel Seg SouthNoitinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Lecturer Jane Fletcher lstName Items RemoveAt 1lstName SelectedIndex 12 O
301. u must select something before deleting it MsgBoxStyle Critical ERROR Exit Sub End If The user has made a valid selection so delete it lstCatalogue Items RemoveAt lstCatalogue SelectedIndex Put the focus back in the text box txtProduct Focus End Sub Private Sub btnDeleteAll Click sender As System Object e As System EventArgs _ Handles btnDeleteAl1l Click Check to see if there is anything in the list box to delete first If lstCatalogue Items Count Then MsgBox You must have something to delete first MsgBoxStyle Critical ERROR Exit Sub End If Dim intResponse As Integer intResponse MsgBox Are you sure you want to delete your entire product catalogue _ MsgBoxStyle YesNo ARE YOU SURE If intResponse vbYes Then The user wants to clear all the items from the catalogue lstCatalogue Items Clear End If txtProduct Focus End Sub End Class ee is 05 Jane Fletcher South Nottingham College pae 0 ee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 13 Recapping with ListBoxes Lecturer Jane Fletcher Exercise 13 1 mt playing and formatting output 2 Fe Enter names of students going on a trip 5 Fe rename Select group Process Students going on trip Delete selected oo fom o ke
302. umber Text Length Then MsgBox You have not entered anything into the first text box _ MsgBoxStyle Critical ERROR txtFirstNumber Focus Exit Sub End If If txtFirstNumber Text Length gt 4 Then MsgBox You have entered a value that is too long MsgBoxStyle Critical Error txtFirstNumber Text txtFirstNumber Focus Exit Sub End If If Not IsNumeric txtFirstNumber Text Then MsgBox You have entered a non numeric value MsgBoxStyle Critical Error txtFirstNumber Text txtFirstNumber Focus Exit Sub End If intFirstNumber txtFirstNumber Text If intFirstNumber lt 1 Or intFirstNumber gt 1000 Then MsgBox You have entered a number out of range MsgBoxStyle Critical ERROR txtFirstNumber Text txtFirstNumber Focus Exit Sub End If If txtFirstNumber Text Length Then MsgBox You have not entered anything into the first text box _ MsgBoxStyle Critical ERROR txtFirstNumber Focus Exit Sub End If If txtSecondNumber Text Length gt 4 Then Ol 120 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 3 Introducing RadioButtons Lecturer Jane Fletcher MsgBox You have entered a value that is too long MsgBoxStyle Critical Error txtSecondNumber Text txtSecondNumber Focus
303. umbers Enabled True btnEquals Enabled True btnDivide Enabled False btnPlus Enabled False btnMultiply Enabled False btnMinus Enabled False Me Height 248 Lecturer Jane Fletcher End Sub Private Sub btnEquals Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnEquals Click Here we re going to use a select case statement rather than a string of If statements Select Case is a form of selection construct It examines whatever you tell the program to use as a determinant and then acts accordingly Work out the answer to the sum Select Case strOperator Case The user picked out to add in the operator bit decAnswer intFirst intSecond Case The user picked to subtract in the operator bit decAnswer intFirst intSecond Case The user picked to divide in the operator bit decAnswer intFirst intSecond Case The user picked to multiply in the operator bit decAnswer intFirst intSecond End Select Concatenate an answer for the label lblAnswer Text intFirst amp amp strOperator amp amp intSecond amp amp decAnswer disable the equals button btnEquals Enabled False Alter the height of the form Me Height 476 End Sub Private Sub NewToolStripMenuItem Click ByVal sender As System Object _ ByVal e As System EventArgs Handles NewToolStripMenuItem Click Put everything back to its original state Me Heig
304. user enters 5 into both text boxes then both conditions are met so the Xor operator returns False since only one can be true to meet the criteria of the Xor If the user enters 10 into both text boxes then neither conditions are met so the Xor operator returns False If the user enters 5 into txtSecondNumber and 10 into txtFirstNumber or the other way around then the Xor operator returns True because only one of the conditions were met AndAlso The AndAlso operator is very similar to the And operator in that it also performs logical conjunction on two Boolean expressions The key difference between the two is that AndAlso exhibits short circuiting behaviour If the first expression in and AndAlso expression evaluates to False then the second expression is not evaluated because it cannot alter the final result and AndAlso returns False If txtFirstNumber Text lt 10 AndAlso txtSecondNumber Text lt 10 Then lblOutcome Text One input is less than 10 End If If the user enters 9 into both text boxes then the AndAlso operator will return True because both conditions are met If the user enters 10 into txtFirstNumber and 9 into txtSecondNumber the AndAlso operator will return False like And However if the user enters 10 into txtFirstNumber it doesn t matter what is entered into txtSecondNumber because the first condition wasn t met so the second one won t be evaluated rll t lt lt i lt i lt i
305. user has clicked on a number button the group box gbNumbers should be disabled 11 The value of the variable bFirst should be set to False to indicate that the first number has now been entered 12 The value of the text of the selected button should be stored in intFirst 13 The height of the form should be adjusted to show gbOperator 14 btnEquals should be disabled at this point so that the user may select either plus minus multiply or divide 15 Once the selection has been made by the user clicking his or her chosen button the height of the form should be altered so that only gbNumbers is visible 16 The text of the button selected should be stored in the variable strOperator 17 gbNumbers must be made accessible again 18 Once the user has clicked his second number then the height of the form should be adjusted to again show gbOperator 19 The value of the text of the selected button should be stored in intSecond 20 Now all buttons in that group box except btnEquals should be disabled 21 When btnEquals has been selected the height of the form should be adjusted to show obAnswer 22 The value of decAnswer should be determined by the nature of the value stored in strOperator using the Select Case method 23 The answer should be displayed in lblAnswer in the following format first number selected operator second number selected equals answer 1 3 4 n 14 6 Jane Fletcher South Nottingham College paee ON
306. ut for your final assignment you will be expected to create your own As a minimum project documentation should include e An overview of the project explaining briefly its purpose e Detail on the inputs to outputs from and processes in the project this may take the form of form designs and dictionaries data dictionaries report dictionaries and structured English see next section e Full structured test data test plans and latterly the results of the test plans e Full and detailed evaluations of the software you have produced including why you used the tools and techniques you selected and what you would do differently if you repeated the project and what you would add if you had more time future enhancements to the system e Full print of commented code e Contents page e Front cover Below is an example of the design documentation up to the dictionary part of a project that adds two numbers together and displays a total An overview of the project This section of the documentation requires a brief explanation as to the purpose of the proposed software An example could be A programmer is required which allows the user to enter two numbers into two separate text boxes The numbers entered should be integers within the range of 1 to 9999 and any invalid input should be highlighted to the user who should be directed to re enter the number s both on the click event of the button mentioned below Once the nu
307. uth Nottingham College J E LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives INDEX Lecturer Jane Fletcher G Grab handles 3 GroupBox i 8 21 22 23 26 28 30 31 106 107 165 GUI 3 248 H Hard coding 3 j i Capping 3 Inbuilt function 3 Information 4 148 Input 4 96 97 113 114 115 117 118 119 120 182 186 249 Integer 70 72 79 81 82 96 97 129 130 138 139 148 158 168 173 174 175 177 179 182 183 190 196 198 201 205 207 211 217 222 224 228 230 233 235 238 239 242 Iteration iii 80 K Keyword 4 L Label i 8 16 19 20 23 28 31 ListBox i vii 8 26 30 33 34 37 81 89 241 242 Loading ii 67 Logical Operator 72 M MenuStrip i iii 2 8 35 36 48 90 241 Modulus 72 Multiplication 72 N Naming conventions i Negation 72 O Object 1 4 8 36 43 70 85 123 126 128 130 131 132 134 136 138 139 140 142 144 146 147 148 149 151 155 158 159 160 166 168 169 170 172 174 175 176 178 181 183 185 187 190 192 195 198 199 200 204 205 207 208 209 212 213 216 217 218 221 224 225 226 227 229 233 234 235 236 242 249 Output 4 6 81 179 223 232 249 E T 240 Jane Fletcher South Nottingham College jE LLL Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma f
308. ven in monetary terms by multiplying the value in declnvoiceAmountEntered by intDiscountRate and dividing the whole by 100 Store the answer into the variable decDiscountGiven e Display the value stored in decDiscountGiven in currency format in lb DiscountAmount e Calculate the amount due to be paid by subtracting decDiscountGiven from decInvoiceAmountEntered and storing the answer in decInvoiceAmountDue f Display the value stored in declnvoiceAmountDue in currency format in lblAmountPayable Extension activities 1 Put a splash screen into the project 2 Put the Help facility onto a separate form 3 Ensure that the user cannot select a date on the DateTimePicker more than one year in the future or one year in the past 4 Add ToolTips O esesesesei aesS 169 Jane Fletcher South Nottingham College pma N Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 9 Formatting numbers Lecturer Jane Fletcher 9 0 Specification for program developed in class Enter your number How many decimal places ee You wanted U decimal places Your value is 123 456 Or did you mean like this 123456 Es You wanted 1 decimal places Your value is 143 45b6 0 Or did you mean like this 14345 6 You wanted 2 decimal places Your value is 123 456 00 Or did you mean like this 1234 56
309. ven Programming edexcel oan SouthNoitinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 11 Creating Web Browsers Lecturer Jane Fletcher Exercise 11 1 1 Ge Courses in Nottingh 0 Education Higher Education Diplomas Apprenticeships 4a lt gt x S 2I Enter URL 4 5 6 T 8 SouthNottinghamCollege iaai iion diiri SNCHome Full Time Courses Part Time Courses 14 16 Provision University Level Employers Intemational Login For a career with a difference JEL 2 CERTIFICATE IN HOUSING PRACTICE sary 2012 Lo io or Tony on About Us Student Support Automotive EMTEC Academy TU Education Vacancies News Latest News Interested in full time Search for a Course College Named Training Provider of courses the Year Apply for a full time course here vances Search South Nottingham College s business i development division SNC Training has been named Training Provider of the Year at At South Nottingham College we have a range of prospectuses to help you choose the Nottingham Training Network NTN SREY _ Taster Events 2011 12 awards on 26 January 2012 Browse a prospectus here Have a look atthe taster events available this year r ASNC New A2 a TRAINING _ Course Guide Read More Take a look atthe oo new Part Time A Z Find us on Prospectus click Facebook A
310. vent Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls ListBox ComboBox controls Lecturer Jane Fletcher Toolbox gt Ee DateTimePicker q A Label El pon A 2 gt ListBox ol fad za List iew ListBox The ListBox control is accessed via the Common Controls section of the Toolbox by clicking on the icon shown here To place a ListBox onto your form click on the ListBox icon in the Toolbox and move across to the form with it When you are at the location on the form qar where you wish the top left hand corner of the ListBox to be left click the mouse and drag across and down to describe your chosen size Notice that the active ListBox has grab handles in the same way that other controls have Notice that the text in the ListBox is the default name of the object starting at ListBox1 and so on You cannot type information directly into a ListBox that has to be done via the Items property in the Properties Window or at run time by the program code What is the difference between a ListBox and a ComboBox The ComboBox object allows the user to type information into it at run time and has a drop down list of items contained within it When the user makes a selection from the ComboBox s list of items the ComboBox resumes its single line shape and displays the user s choic
311. vent Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 14 Printing e Graphics DrawString For you amp strName amp _ we have written this special piece of prose _ MyHeaderFont Brushes Black intX intY Put the title on the page Lecturer Jane Fletcher intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer e Graphics DrawString MyFont Brushes Black intX intY Blank line intY intY intFontHeight e Graphics DrawString Mary had a little lamb _ MyFont Brushes Black intTitleX intY Put the first line on the page intY intY intFontHeight e Graphics DrawString Whose fleece was white as snow _ MyFont Brushes Black intTitleX intY Next line intY intY intFontHeight e Graphics DrawString And everywhere that Mary went _ MyFont Brushes Black intTitleX intY Next line intY intY intFontHeight e Graphics DrawString That lamb was sure to go _ MyFont Brushes Black intTitleX intY Next line intY intY intFontHeight intyY intY intFontHeight e Graphics DrawString T HE END _ MyTitleFont Brushes Black intTitleX intY Put the title on the page This code puts an image on the piece of paper Dim bCorner As New Point 150 645 Establish where you
312. verlay TextImageRelati Overlay The default event for a RadioButton is the CheckedChanged event This is activated when the Status of the RadioButton is altered going from either selected with a green dot in the middle of the RadioButton to deselected no green dot in the middle or vice versa However there are many more other events associated with the RadioButton control which can be explored by ensuring that the RadioButton is selected in the Objects ListBox and pulling down the list in the Events ListBox in the Source Code Editor view as shown over the page pC 24 Jane Fletcher South Nottingham College oS SS a _ M 6 Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Commonly used controls RadioButton control Lecturer Jane Fletcher Formi vh Mecinn1 recto Chechedchanged gt Pu Ip z E O gt r E Private Sub RadioButton1_CheckedChanged ByVal sender As System Object ByVal e As System EventArgs Handles RadioBu End Sub End Class Commonly used Properties of the RadioButton control BackColor Sets the background colour of the RadioButton The default background colour is determined by that of the GroupBox in which it sits but it can be changed using the same method as that applied when altering the form s background colour Bear in mind that when you change the BackColor of a RadioButton
313. view dialog box off in maximised state PrintPreviewDialog1 WindowState FormWindowState Maximized PrintPreviewDialog1 Document PrintDocument1 assign a document to Print Preview control PrintPreviewDialog1 ShowDialog display the PrintPreview dialog box 10 The PrintDocument1_PrintPage event gained by double clicking on the PrintDocument object added to the form should contain the following code and comments in addition to any code that allows the document to print see previous program Dim intCount intAnswer As Integer For intCount 1 To 20 intAnswer intNumber intCount e Graphics DrawString intNumber amp amp intCount amp amp intAnswer amp MyFont Brushes Black intTitleX intY Put the title on the page intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer Next intCount ee F lt lt lt i lt i C C i 6 Jane Fletcher South Nottingham College SS a _ lt amn 5 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 15 Updating information in a ListBox Lecturer Jane Fletcher 15 0 Specification for program developed in class Updating list boxes o Updating list boxes File Update Name Item Object Item Objec
314. where you enter 15 and 25 is the answer 40 And so on 4 The final column should explain why you are doing that test Over the page is a sample plan of structured test data for Exercise 2 1 from page 117 It should address each of the aspects listed above in terms of basic functionality and also data related eH 06 Jane Fletcher South Nottingham College G 2 amp _ C aaa ee Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Testing Projects j Lecturer Jane Fletcher Structured Test Data for Exercise 2 1 Test Form1 Group Why eed 1 Load Basic To check that the form loads correctly and that all objects are in the right a place with the right spelling and with the appropriate colours To check that when the form loads the cursor is placed in txtForename To check that when the Tab key is pressed the cursor moves to txtSurname Test Input into Input into Group Why Num txtForename txtSurname 4 Basic To see if there is an error message displayed if the user doesn t enter anything into txtForename 5 Jane Basic To see if there is an error message displayed if the user doesn t enter anything into txtSurname aaa To see if there is an error message displayed if the user 111111111111 enters too many characters over 20 into txtForename To see if there is an error message displayed if the user e
315. will be back to the main screen of TwoPlusTwooO Now enter 100 into the box alongside the prompt Second Number and click the Process button r TwoPlusTwo from SNC PLC We now have two valid numbers 75 and 100 and TwoPlusTwo First Number 75 shows us the answer Second Number 100 You are now ready to use your TwoPlusTwo software Process Clear Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Testing Projects Lecturer Jane Fletcher Once you have started to implement coding behind your projects you will have to learn how to perform robust testing techniques There are several aspects behind testing with this being the basic aspect e Does each form in the project load correctly with all objects in the right place and with all spelling on the form correct e Does only one instance of a form load e ls the tab order set correctly This means that when you press the tab key control passes to each object in the right order e Does each object allow for enough input to be entered and or displayed e Does each form close correctly Once you ve established the basic aspect of the functionality of the project then the data being input to the project must be tested The tests that should be made here are That data
316. y Gone End If Check to make sure that the buttons are in the right state either enabled because there are still entries in the list box or disabled because the list box is empty CheckForEntries Put the cursor back into the right text box txtName Focus End Sub Private Sub NewToolStripMenuItem_Click sender As System Object e As System EventArgs _ Handles NewToolStripMenuItem Click Get rid of everything lstName Items Clear txtName Text txtName Focus CheckForEntries End Sub Private Sub lstName_Click sender As Object e As System EventArgs Handles lstName Click Change the background colour of the button to update btnUpdate BackColor Color Blue btnProcess BackColor Color Red End Sub End Class ee Se 3 Jane Fletcher South Nottingham College o _ _ a _ aaaa__ aoaa M0 q x Unit 14 Event Driven Programming SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development Example programs 15 Updating information in a ListBox Exercise 15 1 Using parallel list boxes 2 File Price Ordered Remove eT like to buy 4 m6 ered 7 Twilight oreaking Dawn Part Game of Thrones Season 1 The Three Musketeers In Time Triple Play Hugo Tinker Tailor Soldier Spy Real Steel Star Wars The Complete Saga Alien Anthology Drive War Horse Harry Potter The Complete Set Transformers Dark of the Moon
317. yed in lstOutput in the following format a i i With lstOutput Items Add Using named numeric formats Add General Number amp Format decNumber General Number Add Fixed amp Format decNumber Fixed Add Standard amp Format decNumber Standard Add Percent amp Format decNumber Percent Add Currency amp Format decNumber Currency Add Add Using user defined numeric formats Add Q amp Format decNumber Add O 00 amp Format decNumber 0 00 Add HHH 0O amp Format decNumber 0 Add H HHO OO amp Format decNumber 0 00 Add HHH O amp Format decNumber H 0 Add FH HHO OO amp Format decNumber E 0 00 Add O 0 amp Format decNumber 0 0 End With a Ye 5 Jane Fletcher South Nottingham College 2_ _ S we SS 6462 a Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Example programs 10 Using TabControls Lecturer Jane Fletcher 10 0 Specification for program developed in class 1 y Using TabControls 1 ES E M a ental F Choice 2 Selected Choice 1 Name of tab tbChoice1 Text on tab Choice 1 NenuStibt Fil TabControl1 tbMenu TabPage3 tbChoice2 a ee TabPage4 tbChoice3 C a TabPage5
318. you can access Most of the projects you sent will create require you to access the top one Windows a nine sii Form Application Select that 55 Jane Fletcher South Nottingham College Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Starting a new project Lecturer Jane Fletcher 608 WindowsApplicationl Microsoft Visual Studio File Edit View Project Build Debug Team Data Tools Test Window Help eSB i dal BBlAaAlLSE 2 9 A GOld u a FS Debug 2 Gb Ga se BS A 2 eE E amp EE WindowsApplication1 BackgroundWorker i My Project DirectoryEntry Forml vb DirectorySearcher ErrorProvider EventLog FileSystemWatcher HelpProvider a Solution Explorer y aE eles Properties MessageQueue Form1 vb File Properties PerformanceCounter Process BEE SerialPort Build Action Compile Copy to Output Dir Do not copy poy E A E Al r F ta ServiceController Timer 4 Printing iN Pointer EA PageSetupDialog Ea PrintDialog 2g PrintDocument e S inreverdaleg fO 0 trom fh OWarings o messages L PrintPreviewControl Description Column Project Custom Tool Custom Tool Name File Name Form1 vb 4 Dialogs hm Pointer ColorDialog FolderBrowserDialog Build Action A FontDialog How the file relates to the build and deployment 2 OpenFileDialog r
319. you to determine all the conditions to be applied in your program e Because it helps you get P3 on the grading grid There is an example of structured English in the previous section Design documentation Also there is a full example of a specification and the associated structured English over the page ae a OTTT T L C eS 91 Jane Fletcher South Nottingham College p Unit 14 Event Driven Programming edexcel SouthNottinghamCollege BTEC Extended Diploma for IT Practitioners Software Development advancing learning changing lives Structured English Lecturer Jane Fletcher Program specification A program is required which will allow the user to enter two numbers each of which should be within the range of 1 to 100 After the numbers have been entered and proved valid the user should be allowed to select a mathematical operator or and the resulting calculation should be displayed An About feature is also required to tell the user how the program functions The program should be internally documented in full Form designs Processing Numbers Help number to process 1 L J 2 L J Processing Numbers File Help Step 1 Enter number to process Start up screen Menu bar 1 Process 2 J Processing Numbers File Help Step 1 Enter number to process 1 Jan z Process 2 Processing Numbers File Help Step 1 Enter number to process a lt Step
320. ystem EventArgs Handles CloseToolStripMenuItem Click Close the project Me Dispose End End Sub Private Sub btnPrint_Click ByVal sender As System Object ByVal e As System EventArgs _ Handles btnPrint Click Preview the PrintPage object s printpage PrintPreviewDialog1 WindowState FormWindowState Maximized PrintPreviewDialog1 Document PrintDocument1 assign a document to Print Preview control PrintPreviewDialog1 ShowDialog display the PrintPreview dialog box End Sub Private Sub PrintDocumenti1_ PrintPage ByVal sender As System Object ByVal e As _ System Drawing Printing PrintPageEventArgs Handles PrintDocument1 PrintPage Dim MyTitleFont As New Font Courier New 14 FontStyle Underline Dim MyFont As New Font Courier New 12 FontStyle Regular Dim intTitleX intX intY intFontHeight As Integer intTitlex 175 intX 100 set coordinates for first thing to print intY 50 intFontHeight MyFont GetHeight e Graphics height of 1 line of font used normal font not title font e Graphics DrawString How to print from a list box _ MyTitleFont Brushes Black intTitleX intY Put the title on the page intY intY intFontHeight reset Y for next line Y increments and gets further down the page as the report gets longer e Graphics DrawString MyFont Brushes Black intTitlexX intY Blank line intY intY intFontHeight Dim strItem As String Set up this string variable to stor
Download Pdf Manuals
Related Search
Related Contents
QuickGuide_Flystick2.. 潜水調査船「しんかい6500」 利用者の手引き 海洋科学技術 Casio WK7500E1A User's Manual EDS-408A/405A Hardware Installation Guide v5 Anexo Gold's Gym GGBE6974.1 User's Manual HOSPITAL GENERAL PEDIÁTRICO “NIÑOS DE ACOSTA ÑÚ Samsung SC4010 User Manual Copyright © All rights reserved.
Failed to retrieve file