1 / 46

فيجيوال بيسك visual basic

فيجيوال بيسك visual basic

dwikatmo
Download Presentation

فيجيوال بيسك visual basic

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A AN N N NA AJ JA AH H N NA AT TI IO ON NA AL L U UN NI IV VE ER RS SI IT TY Y V VI IS SU UA AL L B BA AS SI IC C. .N NE ET T F FO OR RM MS S M MA AN NA AG GE EM ME EN NT T I IN NF FO OR RM MA AT TI IO ON N S SY YS ST TE EM MS S P PR RE EP PA AR RE ED D B BY Y : : M MO OH HA AM MM ME ED D A AB BD DE EL L K KH HA AL LE EQ Q D DW dwikatmo@najah.edu :facebook.com/dwikatmo : dwikatmo@gmail.com WI IK KA AT T 2 24 4/ /0 01 1/ /2 20 01 19 9 V VI IS SU UA AL L B BA AS SI IC C. .N NE ET T F FO OR RM MS S/ /A AP PP PL LI IC CA AT TI IO ON NS S 1 1. .P PR RO OP PE ER RT TI IE ES S 2 2. .E EV VE EN NT TS S 3 3. .M ME ET TH HO OD DS S Form is a class. Form is the container/Area that holds all controls and makes the interface of the application. AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:1 OF 46

  2. F FO OR RM M O OB BJ JE EC CT T P PR RO OP PE ER RT TI IE ES S O OF F A A F FO OR RM M Name: a name is given to a form in design time to be used later in code. Once a name property is assigned, it cannot be changed later in code. Other properties can be changed at design time or at run time (in code) Property values Controlbox True/False Show/Hide control box MaximizeBox True/False Show/Hide Max/Restore box MinimizeBox True/False Show/Hide Minimize box Opacity 0-100% 0 like glass,1 like cover,0.5 half/half Text Any text Description Icon Icon File WindowState Normal, Minimize, Maximize ShowInTaskBar True/False What is Windows task bar? KeyPreview True/False Register keypress by form RightToLeft Yes/No Form direction Width Any number No. of pixels Height Any number No. of pixels Backcolor Color.red Background color of a form Forecolor Color.blue eg. Forecolor for labels on a form Tag Any value Used as temp value for any type Important note: Use ME when effect will take place on current form or form name if effect will take place on different form AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:2 OF 46

  3. E EV VE EN NT TS S O OF F A A F FO OR RM M Event: it is the name of action that needs a reaction (code to be run upon action) Event Load Click MouseClick MouseDown MouseUp KeyPress KeyDown KeyUp FormClosing Upon closing the form FormClosed After the form is closed Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 'Write code here'For example to initialize variable values End Sub You can ask user if he want to save changes when (before) the form closed Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosing 'If Data changed then ask user whether to save it or not End Sub M ME ET TH HO OD DS S O OF F A A F FO OR RM M If we want to close any form by code written on the form itself, we write Method COMMENTS close Close the form (remove it from memory) - me.close , form1.colse show Show the form - form1.show() showdialog Show the form as dialog –form1.showDialog() Hide Me.hide or form1.hide (remains in memory) Centertoparent Display it centered relative to parent CenterToScreen Display it centered relative to screen The .close() method, will close any form and remove it from memory, we write the form name to be closed as Close form2 (code is written on form2) Close form2 (code is written on form1) Open form2 code COMMENTS When form loaded into memory Any click = MouseDown + MouseUp Mouse is pushed down Mouse is released up =KeyDown + KeyUp Key is pushed down Key is released up formName.close() me.close() form2.close() AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:3 OF 46

  4. What is Dialog mean– it means a form is shown and your action is required before you can go to previous form or any other form) Form2.ShowDialog() (you can’t go back to from1 unless you close form2) Form2.Show()’(you can go back to from1 then again to form2 and so on) Close form2 when clicking on it Me.Close() 'This will close any form that is written on it U US SE E F FO OR RM M E EV VE EN NT TS S, , P PR RO OP PE ER RT TI IE ES S A AN ND D M ME ET TH HO OD DS S U US SI IN NG G E EV VE EN NT T K KE EY YP PR RE ES SS S 1 1. .H HO OW On the event Keypress of the form, you can read the key pressed on the keyboard, (provided that the form keypreview is set to true) T1.Text = e.KeyChar (one character) 2 2. .H HO OW W T TO O C CH HA AN NG GE E T TH HE E K KE EY Y P PR RE ES SS SE ED D W If Asc(e.KeyChar) = Asc(vbCrLf) Then SendKeys.Send(vbTab) The same is applied if you want to prevent keyboard from writing letters in a textbox, only allow numeric textbox to accept numbers from 0 to 9 an minus -, and dot . ASCII code for 0 is 48, for 9 is 57, for minus sign is 45, for dot . is 46 We write the following code on keypress event Select Case Asc(e.KeyChar) Case 48 To 57, 45, 46 Case Else e.KeyChar = "" End Select 2 2 W To see the form properties press F4, change it, run to see changes you can also change the properties by code (except the name) assume we have form1 or you can change it by code like this Form1.Text = "ةشاشلاةيسيئرلا" W This means we can create object that is identical to the original class, for example this code Dim f As New Form1 f.Show() Whenever executed, create a copy of the form f1, then display it. Please note that any object created is hidden (Not visible) by default. W T TO O R RE EA AD D A A K KE EY Y T TH HA AT T I IS S P PR RE ES SS SE ED D O ON N A A F FO OR RM M WI IT TH H A AN NO OT TH HE ER R O ON NE E ( (C CH HA AN NG GE E E EN NT TE ER R T TO O T TA AB B) ) WA AY YS S T TO O C CH HA AN NG GE E P PR RO OP PE ER RT TI IE ES S O OF F A AN N O OB BJ JE EC CT T( (f fo or rm m o ob bj je ec ct t h he er re e) ) WH HY Y F FO OR RM M I IS S C CO ON NS SI ID DE ER RE ED D A AS S C CL LA AS SS S AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:4 OF 46

  5. H HO OW Me.Text = "Main Screen" Me.ShowInTaskbar = True Me.BackColor = Color.Black Me.Cursor = Cursors.Hand Me.ForeColor = Color.Chocolate Me.MaximizeBox = False Me.MinimizeBox = False Me.ControlBox = False Me.Opacity = 0.88 W T TO O H HA AN ND DL LE E F FO OR RM M P PR RO OP PE ER RT TI IE ES S U US SI IN NG G C CO OD DE E Change main title 1 Not transparent, 0 fully transparent like glass Me.Width = 500 Me.Height = 500 Me.RightToLeft = True If you want to change property of form (fSales) but the code is written on another form, replace me by fsales as fSales.Text = "Main Screen" fSales.BackColor = Color.Black Task1 Create 2 forms, on click event of form1, write Form2.show On click event of form 2, write Me.colese Self evaluation questions Write the vb.net code to accomplish the following of form1 Change the main title to be Payroll system. Make the form visible on taskbar Hide the minimize box Set the form to be right to left Display form1 as dialog form Which event you use to read any key pressed on the form, which property should be used to make it works, what is its value Event :Keypress, Property: KeyPreview, Value true AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:5 OF 46

  6. C CO OM MM MA AN ND D B BU UT TT TO ON NS S / /T TE EX XT TB BO OX XE ES S A AN N N NA AJ JA AH H N NA AT TI IO ON NA AL L U UN NI IV VE ER RS SI IT TY Y M MA AN NA AG GE EM ME EN NT T I IN NF FO OR RM MA AT TI IO ON N S SY YS ST TE EM MS S 2 24 4/ /0 01 1/ /2 20 01 19 9 V VI IS SU UA AL L B BA AS SI IC C. .N NE ET T B BU UT TT TO ON NS S A AN ND D T TE EX XB BO OX XE ES S 4 4. .P PR RO OP PE ER RT TI IE ES S 5 5. .E EV VE EN NT TS S 6 6. .M ME ET TH HO OD DS S P PR RO OP PE ER RT TI IE ES S O OF F A A T TE EX XT TB BO OX X O OB BJ JE EC CT T A AS SS SU UM ME E W Property Name WE E H HA AV VE E A A T TE EX XT TB BO OX X N NA AM ME E T T1 1 Code to change it Can’t be changed by code Values True/False AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:6 OF 46

  7. True/False True/False True/False True/False True/False True/False True/False True/False Yes/No Any Mask 0 unlimited Valid No. As Temp Any value Can’t be changed by code T1.enabled =false T1.MultiLine=True T1.ReadOnly=True T1.visible =False Locked Enabled Multiline ReadOnly Visible UseSystemPasswordCharT1.UseSystemPasswordChar = True TabStop T1.TabStop = True WordWrap T1.WordWrap =True RightToLeft T1.RightToLeft = RightToLeft.No PasswordChar T1. PasswordChar= "*" MaxLength T1.Maxlength =5 TabIndex T1.TabIndex = 0 Tag T1.tag=any Text (most used) T1.text = "Hello" ScrollBars T1.ScrollBars=ScrollBars.Horizontal T1.ScrollBars=ScrollBars.Vertical T1.ScrollBars=ScrollBars.Both T1.ScrollBars=ScrollBars.None TextAlign T1.TextAlign = HorizontalAlignment.Center T1.TextAlign = HorizontalAlignment. Left T1.TextAlign = HorizontalAlignment. Right Dock (ءاسرا) T1.Dock = DockStyle.Bottom DockStyle.Left, DockStyle. Right DockStyle. fill, DockStyle.Button DockStyle. top, DockStyle.none Forecolor T1.forecolor =color.red BackColor T1.BackColor = Color.Yellow Width T1.width=200 Height T1.height=200 TextLength T1.TextLength Notes: for PasswordChar to take effect, UseSystemPasswordChar should be set to False Note: For WordWrap and scrollbars to take effect, Multiline should be true For a TextBox named T1 Write a VB.net code to 1.set the Password mask to be & T1.UseSystemPasswordChar = False T1.PasswordChar= "&" 2.set the text Box accept Arabic properly in T1, And accept English properly in T2, where the code should be written T1.RightToLeft = RightToLeft.Yes T1.TextAlign = HorizontalAlignment.Right ‘for English write T2.RightToLeft = RightToLeft.No T2.TextAlign = HorizontalAlignment.Left The code is written in the GotFocus Event of each textbox 3.To set a textbox not accept more than 7 characters/numbers 4.Or to prevent textbox from accepting more than 7 characters/numbers T1.MaxLength = 7 E EV VE EN NT TS S O OF F A A T TE EX XT TB BO OX X Horizontal Vertical Both None Center Left Right Color.Name In pixels In pixels No of letters AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:7 OF 46

  8. Event TextChanged Any change in the content Click A click by a mouse/touch GotFocus Cursor arrives in the textbox LostFocus Cursor leaves the textbox KeyPress Any key is pressed from keyboard = KeyDown + KeyUp KeyDown Any key is pushed down KeyUp Any key is released up MouseClick A click by a mouse MouseDown When mouse is pushed down MouseUp When mouse is released up MouseEnter Mouse enters Textbox area MouseLeave Mouse leaves Textbox area MouseHover Mouse Hovers in Textbox area Where to write code of the event? Private Sub txtUserName_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtUserName.TextChanged 'here End Sub Jawwal Number is 10 numbers write a code to test if its length is correct, if not alert the user, set cursor back to T1 Private Sub T1_LostFocus(sender As Object, e As System.EventArgs) Handles T1.LostFocus If T1.TextLength < 10 Then MessageBox.Show("incorrect Jawwal Number") T1.Focus() End If End Sub M ME ET TH HO OS S O OF F A A T TE EX XT TB BO OX X Method usage comments Focus T1.focus() Go to T1/ cursor will set in T1 Copy T1.copy() Copy T1 contents or selected text Cut T1.cut() cut T1 contents or selected text Clear T1.clear() clear T1 contents SelectAll T1.SelectAll() Select all T1 contents DeselectAll T1.DeselectAll deselect T1 contents AppendText T1.AppendText("any") Add a text to T1 Undo T1.Undo() Undo changes in T1 Paste T1.Paste() Paste a text in T1 Note: Copy and cut will put the text in clipboard, while clear won’t. What the following code will do? How to read data from textboxes (Used as input) Dim s as string S = T1.text Dim Y as integer Y = val(T1.text) When invoked comments Most Used event = MouseDown + MouseUp AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:8 OF 46

  9. Dim d as date D = cdate(T1.text) L LA AB BE EL LS S Labels inherit most of the TextBox properties, events and methods, except that it is different in appearance and read only (can’t be used as input). autoSize is a property of a label set to true or false if it is true the size of the label will increase automatically to fit the text inside the label. C CO OM MM MA AN ND D B BU UT TT TO ON NS S Command Buttons share most of the TextBox properties, events and methods, except that it is different in appearance and read only (can’t be used as input). Text property change the caption appear on the button, however, we can make a shortcut for the command button. What is the shortcut: it is a combination between Alt and a letter, in case of pressing it; it will invoke the click event (if no mouse exists) For example setting the text property to E&xit will appear as Exit, It means if a user presses Alt and X, it invoke the click method of that command Button. We can change it also using code cmdExit.text= "E&xit" Note: in the Notepad the shortcuts appear as follows (in menu) The same is applied for the command button If you press on alt+x , the same as clicking the button G GR RO OU UP P B BO OX X This is just a rectangle to group some controls together, it is used mainly for separating check boxes’ groups and radio buttons’ groups to be one block Properties : Text, RightToLeft, Dock, tag, visible etc.. C CH HE EC CK K B BO OX XE ES S These allow user to select multiple answers AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:9 OF 46

  10. Here we have 5 checkboxes, assume the first one name is chkFacebook, then we can read its value by using the event CheckedChanged Facebook = chkFacebook.checkstate If it is checked it has value of 1, if not checked, it has value of 0 Or as Boolean value Facebook = chkFacebook.checked If it is checked it has value of True, if not checked, it has value of False You can set its value also by using code chkFacebook.checked = true or chkFacebook.checked =false chkFacebook.checkstate =1 or chkFacebook.checkstate = 0 R RA AD DI IO O B BU UT TT TO ON NS S These allow user to select only one answer Here we have 2 radio buttons, assume their names are optMale and optFemale How to read their values? By using the event CheckedChanged Dim Male as Boolean Male = optMale.checked If it is checked it has value of True, if not checked, it has value of False You can set its value also by using code optMale.checked = true or optMale.checked = false L LI IN NK KE ED DL LA AB BE EL L It is like a label, but it has hyperlink. Properties Text : text appear on it Event LinkClicked Code Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked Process.Start("https://www.najah.edu/ar/") End Sub S ST TA AN ND DA AR RD D N NA AM MI IN NG G C CO ON NV VE EN NT TI IO ON NS S I IN N V VI IS SU UA AL L B BA AS SI IC C Control Example/Purpose form main TextBox Password TextBox Age CommandButton Save CommandButton Cancel label Password RadioButton Male CheckBox FaceBook Name frmMain txtPassword txtAge btnSave btnCancel lblPassword radMale chkFaceBook prefix frm txt txt btn btn lbl rad chk AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:10 OF 46

  11. comboBox ListBox Menu Following the standard naming conventions will have a great benefit in clearing ambiguity for the events when writing code btnSave,btnCancel.. txtUserName,txtPassword etc,.. chkMale, chkFemale .. mnuEdit, mnuCopy, mnuCut, mnuPaste.. File mnuFile cbo lst mnu U US SI IN NG G A AR RR RA AY YS S NEW ONE DIMENSIONAL ARRAYS MULTIDIMENSIONAL ARRAYS S ST TR RI IN NG G A AR RR RA AY YS S ONE DIMENSIONAL (SIZED)ARRAYS We want to save day names in an array Method 1 Dim Days(6) As String ' same as Dim Days(0 To 6) As String Days(0) = "Sunday" : Days(1) = "Monday" etc… Method 2 Dim Days() As String Days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} Method 3 Dim Days() As String = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} How to read and save an array element AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:11 OF 46

  12. X = grades(4) 'Put fifth grade in variable x grades (4) = 58 'Put 58 into 5th element fifth grade How many elements exist in Grade Array Grades.length Array is considered as class How comes? 'how many elements in grades array Grades.length Property 6 Array.Sort(Grades) method Array.Reverse(Grades) method Array.IndexOf(Grades, 98) method Grades.Max method Grades.Min method Grades.Sum method Grades.Average method Sort ascending Reverse sorted returns index of value 98, -1 if doesn’t exist 98 55 476 79.3 STRING ARRAYS How to deal with string variables A string array colors contain 4 color names Dim colors() As String = {"Red", "Green", "Blue", "White"} a sting variable color contains color name Dim color As String = "Magenta" By default, string variable could be used as variable and as array. As variable Set its value color = "Green" Get its value x = color However, in VB.net string variable could be used as array of characters Dim color As String = "Magenta" Is represented as array of 7 elements (from 0 to 6) Index 0 1 2 3 4 5 6 Value M a g e n t a And we can use loops to check every single character For I = 0 To color.Length - 1 AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:12 OF 46

  13. Console.WriteLine(color(I)) Next How to cipher a string by replacing every character with the next character ? Dim S As String = "An Najah National University" Dim temp As String For I = 0 To S.Length - 1 temp = temp & Chr(Asc(S(I)) + 1) Console.WriteLine(Chr(Asc(S(I))) & vbTab & Chr(Asc(S(I)) + 1)) Next S = temp Console.WriteLine(S) Console.ReadKey() This code will replace next character by current character, for example it will replace b by a, o by n, k by h and so The output will be as Bo!Obkbi!Obujpobm!Vojwfstjuz instead of An Najah National University Dim X(5) As Integer Index 0 1 2 3 Value X = {2, 4, 5, 7, 1, 0} Index 0 1 2 3 Value 2 4 5 7 X(0) = 2 : X(1) = 4 : X(2) = 5 : X(3) = 1 : X(4) = 0 Dim A(1, 2) As Integer Row/col 0 1 2 0 1 A = {{4, 5, 2}, {8, 6, 1}} Row/col 0 1 2 0 4 5 2 1 8 6 1 ' or set its value for each element A(0, 0) = 4 : A(0, 1) = 5 : A(0, 2) = 2 A(1, 0) = 8 : A(1, 1) = 9 : A(1, 2) = 5 4 5 4 1 5 0 AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:13 OF 46

  14. How to get the last Row Index above (2) ' it means 3 columns First Dimension is A.GetUpperBound(0) How to get the last Row Index above (1) ' it means 2 Rows Second Dimension is A.GetUpperBound(1) How many Rows the previous Array have? How many Columns the previous Array have? 'loop and print all the elements 'One Dimensional Array For i = 0 To X.Length - 1 t1.text = t1.text & X(i) & vbCrLf Next 'loop and print all the elements '2 Dimensional Array T1.Text = T1.Text & "Printin 2 dimensional array" & vbCrLf For i = 0 To A.GetUpperBound(0) For j = 0 To A.GetUpperBound(1) T1.Text = T1.Text & A(i, j) & vbTab Next T1.Text = T1.Text & vbCrLf Next EXAMPLES Write a code to find the sum of integer array elements, find maximum, minimum values and print them AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:14 OF 46

  15. U US SI IN NG G A AD DV VA AN NC CE ED D F FU UN NC CT TI IO ON NS S/ /S SU UB BS S Iteration vs. Recursion Passing Parameters by reference Passing Arrays as parameters Optional Parameters Overloading I IT TE ER RA AT TI IO ON N V VS S. .R RE EC CU UR RS SI IO ON N Iteration is done by using loops, while recursion means the function call itself. Principle in recursion, if we can find or calculate process N times, we can decompose it in N + (N-1) + (N-2) till the stopping rule. For example, instead of using the loop to sum from 1 to 5, we can use recursion to sum it as follows Sum (5) is 5 + Sum (4) 5 + 4 + Sum (3) 5 + 4 + 3 + Sum (2) 5 + 4 + 3 + 2 5 + 4 + 3 + 2 It works using a stack exactly like the following steps Stack Rule: Last in First Out (LIFO) number is 1, it is removed first, and so on + + Sum (1) 1 لاوأ م دخ ي اريخأ لصاولا . Last done Sum(1) 1 AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:15 OF 46

  16. + + + Sum(2) 2 2 2 + + + + + Sum(3) 3 3 3 3 3 + + + + + + Sum(4) 4 4 4 4 4 4 4 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 Sum(5) 1 3 6 10 15 Ans. start Step1 Step2 Step3 Step4 Step5 Step6 Step7 Step8 Step9 stop Write a function using iteration to sun from N to 1 Function Sum (ByVal N as Integer) As Long Dim S As Long For i = N To 1 Step -1 S += i Next Return s End Function For recursion, there should be a stopping rule (here we stop at 1), the above is written in VB.net as Function Sum (ByVal N as Integer) As Long If N = 1 Then Return 1 'Stopping Rule Return N + Sum (N - 1) End Function Write a VB.net functions using recursion to calculate the followings 1.Factorial of a number Function Factorial (ByVal N As Integer) As Long If N = 1 or N = 0 Then Return 1 'Stopping Rule Return N * Factorial (N - 1) End Function A fractal is a geometrical figure, but unlike triangles, circles, and rectangles, fractals can be divided into parts, each of which is a reduced-size copy of the whole. There are many interesting examples of fractals. A Sierpinski triangle is a pattern of recursive triangles. AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:16 OF 46

  17. Write a function using recursion to Calculate M(i) = 1 + Function M(ByVal i As Integer) As Double If i = 1 Then Return 1 Return (1 / N) + M(i - 1) End Function Calculate M(i) = Function M(ByVal i As Integer) As Double If i = 1 Then Return 1 / 3 Return (i / (2 * i + 1)) + M(i - 1) End Function Calculate M(i) = Function M(ByVal i As Integer) As Double If i = 1 Then Return 1 / 2 Return (i / (i + 1)) + M(i - 1) End Function Print the characters in a string reversely Print the digits in an integer reversely Function P(ByVal S As String) As String If S.Length = 1 Then Return S Return S.Substring(S.Length - 1, 1) & P(S.Substring(0, S.Length - 1)) End Function Occurrences of a specified character in a string) Write a recursive method that Finds the number of occurrences of a specified letter in a string using the following method header: AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:17 OF 46

  18. Sum the digits in an integer using recursion Function SumDigits(ByVal N As Integer) As Long If N < 10 Then Return N Return (N Mod 10) + Sum((N - N Mod 10) / 10) End Function Fibonacci series Public Function Fib(ByVal N As Integer) As Integer If N <= 2 Then Return 1 Return Fib(N - 1) + Fib(N - 2) End Function Call it, explore the Golden Ratio For i = 1 To 25 T1.Text = T1.Text & i & vbTab & Fib(i) & vbTab & (Fib(i) / Fib(i - 1)).ToString("#.#00") & vbCrLf Next P PA AS SS SI IN NG G P PA AR RA AM ME ET TE ER RS S B BY Y R RE EF FE ER RE EN NC CE E 1.Write a sub Swap that accept 2 variables x and y as parameters, then swap them, test it. Print values of x,y before swap and after swap. Hint: you should pass parameters by reference Sub Swap(ByRef x As Integer, ByRef y As Integer) Dim Temp As Integer Temp = x x = y y = Temp End Sub Dim A As Integer = 10, b As Integer = 7 T1.text = "before Swap " & vbcrlf T1.text = T1.text & "a = " & A & " b = " & b & vbcrlf Swap (A, b) T1.text = T1.text & "After Swap " & vbcrlf T1.text = T1.text & "a = " & A & " b = " & b O OP PT TI IO ON NA AL LP PA AR RA AM ME ET TE ER RS S Write a function that calculate salary tax for an employee, if the employee is Married, tax is 10% of the salary, if the employee is single, then tax is 15% of the salary, by default, consider employee as being Married Function CalcTax(ByVal salary As Double, Optional ByVal Status As String = "Married") As Double AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:18 OF 46

  19. If Status = "Married" Then Return salary * 0.1 Else Return salary * 0.15 End If End Function How to call it? Dim Tax as double Tax = CalcTax(100, "Single") Tax = CalcTax(100, "Married") You can call it without the second parameter, because if you didn’t specify it, it is considered by default as Married. Tax = CalcTax(100) same as Tax = CalcTax(100, "Married") tax will be 10 tax will be 15 tax will be 10 AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:19 OF 46

  20. A nother example with 2 optional parameters Function CalcTax2(ByVal salary As Double, Optional ByVal Gender As String = "Male", Optional ByVal Status As String = "Married") As Double If Status = "Married" Then If Gender = "Male" Then Return salary * 0.10 Else Return salary * 0.12 End If Else If Gender = "Male" Then Return salary * 0.15 Else Return salary * 0.18 End If End If End Function 'here we have 3 parameters which are salary, Gender, Status 'How to call it txtTax.Text = CalcTax2(100) 'use salary only txtTax.Text = CalcTax2(100, "Male")'use salary and Gender 'use salary, gender and status txtTax.Text = CalcTax2(100, "Male", "Single") txtTax.Text = CalcTax2(100, , "Male")'use salary, And status only O OV VE ER RL LO OA AD DI IN NG G Overloading means: defining multiple functions with the same name but with different parameters. W WH HY Y D DO O W it is useful, when the data type of a passed parameter is not the same, and we need to call the function with different data types, instead of defining different functions with different names, we use one function name, but with different parameter data types. For example, if we have a function Function abs(ByVal x As Integer) As Integer Return IIf(x < 0, -x, x) End Function If we call is to find the absolute value of -6.254, it will return 6 only, for that, we continue to define the same name for double data types and other data types Function abs(ByVal x As Double) As Double Return IIf(x < 0, -x, x) End Function Function abs(ByVal x As SByte) As SByte Return IIf(x < 0, -x, x) End Function WE E N NE EE ED D T TO O U US SE E O OV VE ER RL LO OA AD DI IN NG G? ? AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:20 OF 46

  21. C CA AL LL LI IN NG G A A F FU UN NC CT TI IO ON N F FR RO OM M A AN NO OT TH HE ER R F FU UN NC CT TI IO ON N Write the correct code to calculate the following formula, use functions only Sum the digits in an integer. Write a function that computes the sum of the digits in an integer. For example, SumDigits(234) returns 9 (2 + 3 + 4). (Hint: Use the % operator to extract digits, and the / operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To remove 4 from 234, use 234 / 10 (= 23). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program that prompts the user to enter an integer and displays the sum of all its digits. Function SumDigits(N As Integer) As Integer Dim Temp As Integer, Remainder As Integer Temp = N Mod 10 Remainder = (N - Temp) / 10 If Remainder = 0 Then Return Temp Return Temp + SumDigits(Remainder) End Function Another simpler example for any number of digits Function SumDigits(N As String) As Integer Dim sum As Integer For i = 0 To N.Length - 1 sum = sum + Val(N(i)) Next Return sum End Function Call it from click on command button as T2.Text = SumDigits(T1.Text) AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:21 OF 46

  22. 1 1. .D DA AT TE E C CL LA AS SS S ( (D DE EF FI IN NE E) ) 2 2. .U US SI IN NG G T TI IM ME ER R 3.D DA AT TE E M ME ET TH HO OD DS S D DA AT TE E C CL LA AS SS S Date is considered as class, we can create an Object of Data Class 'Define Empty Date Dim d As Date = New Date 'Set its value to current Date and Current Time d = Now() 'Put its value in a textBox txtDate1.Text = d D DA AT TE E P PR RO OP PE ER RT TI IE ES S if we have a date class variable named d, its value is 08/12/2020 10:04:22 AM then Property usage Date d.Date() TimeOfDay d.TimeOfDay.ToString 10:04:22 Second d.Second() Minute d.Minute() Hour d.Hour() Day d.Day() Month d.Month() Year d.Year() DayOfWeek d.DayOfWeek() DayOfYear d.DayOfYear() DayOfWeek gives the day number in a week, 0 for Sunday, 1 for Monday,. . . 5 for Friday, 6 for Saturday. DayOfYear gives the day of a year from 1 to 365 T TI IM ME ER R A Timer control is important in viewing Date/Time It has only one Event (Tick) used to run any code written in it every Interval Properties Interval in Miliseconds (1000 = 1 second) Enabled : by default it is set to False, to make it running set it to true Example: Add a label name it lblDateTime, add a timer, set the enabled to true, interval to 100, on the tick event write the following code Value 08/12/2020 12:00:00 22 4 10 8 12 2020 2 343 AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:22 OF 46

  23. Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick lblDateTime.Text = Now() End Sub You can separate it into 2 labels, one for date, and one for time. On the tick event of the timer, add this code (you should have label1 and label2 added to the form) Dim d As New Date d = Now() Label1.Text = d.ToString("dd/MM/yyyy") Label2.Text = d.ToString("HH:mm:ss") D DA AT TE E M ME ET TH HO OD DS S D DA AT TE E/ /T TI IM ME E D DI IF FF FE ER RE EN NC CE E Y YO OU U C CA AN N F FI IN ND D T TH HE E D DI IF FF FE ER RE EN NC CE E B BE ET TW WE EE EN N T TW WO O D DA AT TE ES S ( (W WH HY Y) ) Dim DOB As Date Dim Today As Date = Now() DOB = CDate(txtDOB.Text) txtYears.Text = DateDiff(DateInterval.Year, DOB, Today) txtMonths.Text = DateDiff(DateInterval.Month, DOB, Today) txtDays.Text = DateDiff(DateInterval.Day, DOB, Today) Y YO OU U C CA AN N F FI IN ND D T TH HE E D DI IF FF FE ER RE EN NC CE E B BE ET TW WE EE EN N T TW WO O T TI IM ME ES S ( (W WH HY Y) ) Dim SignIn As Date Dim SignOut As Date SignIn = CDate(txtSignIn.Text) SignOut = CDate(txtSignOut.Text) txtHours.Text = DateDiff(DateInterval.Hour, SignIn, SignOut) txtMimutes.Text = DateDiff(DateInterval.Minute, SignIn, SignOut) txtSeconds.Text = DateDiff(DateInterval.Second, SignIn, SignOut) A AD DD DI IN NG G V VA AL LU UE ES S T TO O A A D DA AT TE E You can add any value to a given date (add a years, Months, days, Hours, minutes, or seconds) Dim d As New Date d = CDate(txtDate.Text) d = d.AddYears(1) txtDate.Text = d The same is applied for adding days,months etc.. d = d.AddMonths(1) d = d.AddDays(1) d = d.AddSeconds(1) d = d.AddHours(1) another method to add to Date d = d.AddMinutes(1) d = d.AddMiliseconds(1) AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:23 OF 46

  24. d = DateAdd(DateInterval.Year, 10, d) d = DateAdd(DateInterval.Month, 10, d) d = DateAdd(DateInterval.Day, 10, d) d = DateAdd(DateInterval.Hour, 10, d) AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:24 OF 46

  25. STRING CLASS STRING METHODS Dim S as String = "Good Morning" Method Name S.Length /This is a property 12 S.Substring(8) S.Substring(5, 3) S.Replace("o", "i") S.Remove(1, 2) S.ToUpper() S.ToLower() S.indexOf("d") S.IndexOf("o") S.LastIndexOf("o") S.Trim() String.concat("Al","i") String.compare("a","b") String.compare("a","a") String.compare("a","A") S.Length : Gives the number of symbols/characters S.Substring(8) : gives the 8th character and any leading characters S.Substring(5, 3) : Gives 3 characters starting from position 5 – included which are (6th,7th, and 8th characters) S.Replace("o", "i") will replace the o with i S.Remove(1, 2) : will remove 2 characters starting from position 1 (2nd character -Included) which are oo S.indexOf("d"): will give the location of first occurrence of the letter specified. S.LastindexOf("d"): will give the location of last occurrence of the letter specified. S.IndexOf("o", 2): will give the position of o starting from position 2 S.Trim():Removes spaces before and after a string for example if s = " Good ",its value after trim will be "Good" Value Number of characters 9th character & after it Start from 6th ,3 chars ning Mor Giid Mirning Replace o with i Gd Morning Remove 2nd 3rd letters GOOD MOORNING Change to CAPS good morning Change to Small 3 Location of d 1 Location of 1st O 6 Last location of o Remove spaces around S Ali Concating 2 texts False Compare 2 values True Depends on ?? AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:25 OF 46

  26. Method Name S.Insert(3, "W") S.Remove(5, 4) S = S.Replace("A", "H") Replace any A with H Dim S As String S = "Two or more Students" T1.Text = S & vbCrLf S = S.Insert(11, " distinct") T1.Text = T1.Text & S & vbCrLf S = S.Remove(0, 7) T1.Text = T1.Text & S & vbCrLf S = S.Replace("S", "s") T1.Text = T1.Text & S & vbCrLf T1.Text = T1.Text.Replace("i", "O") As Textbox is considered as a class, its Text value also is considered as a class, so we can treate all previous methods and apply them on T1.text as follows You can replace any string variable above by T1.text In T1, replace ant I with O T1.Text = T1.Text.Replace("i", "O"), and so on for other methods. Change all content of T1 to Capital Letters T1.text=T1.text.ToUpper Change all content of T1 to Small Letters T1.text=T1.text.ToLower Extra methods that applied to T1 directly (but not to a string variable or T1.text) Having a textbox T1, then Method Name What it does T1.cut() Cut the selected text in t1 and saves it in clipboard T1.copy() copy the selected text in t1 and saves it in clipboard T1.paset() Paste the text from clipboard into current location in t1 T1.clear() Clears/deletes all the contents of T1 Create a textbox on a form, implement the previous methods on it. What it does Insert letter W, in 4th location Remove 4 characters starting at 6th location AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:26 OF 46

  27. Question: Validate an email address to be valid before leaving a textbox, if it is not correct, go back to T1. Email address like dwikatmo@najah.edu Write a function that counts the occurrences of a specified character in a string. For example, if we have s = "duplicate id’s is done by adding the same id as many times as we can", and we want to count how many d exist in S. the output will be The function returns d occurred 6 times Write a function that validate a Jawwal phone number written in a textbox, valid phone number as 0599565816. First 3 characters should be 059 Total number of digits should be 10 exactly. How to deal with numbers as text Numbers could be treated as text (Not vice versa) Question: having a three digit number like 784, find ones here it is 4,tens here it is 8, and hundreds here it is 7 of that number 784 = 7 hundreds + 8 tens + 4 ones Dim N As Integer, S As String N = Val (T1.Text) S = N.ToString("00#") Dim Ones As Byte, Tens As Byte, Hundreds As Byte Ones = S.Substring(2, 1) Tens = S.Substring(1, 1) Hundreds = S.Substring(0, 1) You can solve it recursively buy using Mod Function SumDigits(N As Integer) As Integer Dim Temp As Integer, Remainder As Integer Temp = N Mod 10 Remainder = (N - Temp) / 10 If Remainder = 0 Then Return Temp Return Temp + SumDigits(Remainder) End Function Question: depending on previous question, write a function NumToWord that Accept a 3-digit integer number, then return its equivalent in English words as string. For example the function will accept 784 as parameter, and return a string which is Seven Hundreds eighty four AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:27 OF 46

  28. Hint: You may create 3 functions and gather the result or one function with an array of individual numbers by using a loop. Reverse Integer 5478 becomes 8745 Function ReverseInteger(N As Integer) As String Dim Temp As Integer, Remainder As Integer Temp = N Mod 10 Remainder = (N - Temp) / 10 If Remainder = 0 Then Return Temp Return Temp & ReverseInteger(Remainder) End Function H HA AN ND DL LI IN NG G T TE EX XT T F FI IL LE ES S Open Text File Save Text Files Enhance Using Dialogs When we deal with files, we are interested in 3 parts which are Drive Path File extension File name For example a full qualified name of a file might as follows C:\documents\cv\Ahmad.txt D:\documents\received\ali.txt D:\documents\Sent\EULA.txt AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:28 OF 46

  29. Drive C:\ D:\ D:\ So, if we want to open a file, we should know the fully qualified name As D:\documents\Sent\EULA.txt This raises the need to have a text variable that holds the file name to be opened or saved Public f as String = "D:\documents\Sent\EULA.txt" How to open the text file ,display its contents inside a textbox (Name T1) Dim objReader As New System.IO.StreamReader(f) T1.Text = objReader.ReadToEnd objReader.Close() How to save the contents of a textbox (Name T1) into text file Dim objWriter As New System.IO.StreamWriter(f) objWriter.Write(T1.Text) objWriter.Close() You can enhance your code by changing the previous codes into subs or functions Sub OpenTextFile() Dim objReader As New System.IO.StreamReader(f) T1.Text = objReader.ReadToEnd objReader.Close() End Sub Sub SaveTextFile() Dim objReader As New System.IO.StreamReader(f) T1.Text = objReader.ReadToEnd objReader.Close() End Sub Path documents\cv\ documents\received\ ali documents\Sent\ FileName Ahmad Extension .txt .txt .txt EULA AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:29 OF 46

  30. How to detect if the user has made changes to the contents of the file? (For opened file, if the user didn’t make any changes, when he closing the program, do nothing. But if he made changes, prompt (ask) the user if he want to save changes or not. We need a flag variable default value is false, if user made changes set it to true, when closing check it, if its value is true, ask the user to save or not. Public flag As Boolean = False On which event? in the textbox event TextChanged Flag = True Other tasks for text files AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:30 OF 46

  31. F FO OR RM MA AT TT TI IN NG G D DA AT TA A N Nu um me er ri ic c f fo or rm ma at t D Da at te e F Fo or rm ma at t F FO OR RM MA AT TT TI IN NG G D DA AT TA A ( (N NU UM MB BE ER RS S A AN ND D D DA AT TE ES S) ) Formatting data means display the value with different format, but keep the same value when reading it as displaying 25 as 00025, or displaying 1/05/2017 as 01/May/2017 F FO OR RM MA AT TT TI IN NG G N NU UM MB BE ER RS S The symbol # denotes a number or a digit The symbol 0 denotes the fill How to display a number 5214458.2135 with one thousand separator and just 2 decimal points as 5214458.21 AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:31 OF 46

  32. Dim x as double = 5214458.2135 T1.text = x.tostring(“#.##”) How to display the following numbers as (write code) Assume original is saved in x variable Original Number Formatted Number 1 0001 9 09 599868520 599868520 0598545625 059-8545-625 0598545625 (059) 8545 625 2560 $2560 12265422.213 12,265,422.21 12265422.213 $12,265,422.21 25124 2 5 1 2 4 F FO OR RM MA AT TT TI IN NG G D DA AT TE ES S/ /T TI IM ME ES S Date could be displayed in any way you need, just put the mask, and the displayed value will match the mask you put. If you use any symbol/character in a mask other than predefined masks, it will be displayed as it is. If a date = 08/12/2020 10:04:22 AM Predefined different masks used. M MA AS SK K V VA AL LU UE E M MA AS SK K d 08/12/2018 h dd 08 hh ddd Tue m dddd Tuesday mm M December 08 s MM 12 ss MMM Dec MMMM December tt YY 20 H HH H YYYY 2020 H H Note that M (Capital M) is used for Month, m (Small m) is used for minute How to format a date as code x.ToString("000#") x.ToString("0##-####-###") x.ToString("(0##) #### ###") x.ToString("$#") V VA AL LU UE E 10 10 4 04 22 22 AM/PM 2 24 4 E ER RR RO OR R AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:32 OF 46

  33. 30/01/2018 Original Date Formatted Date 30/01/2018 January 30/01/2018 30 30/01/2018 JAN 30/01/2018 Jan/2018 30/01/2018 Tue-Jan 30/01/2018 Jan/30 30/01/2018 Jan/2018 30/01/2018 Tuesday/2018 10:03:22 22 10:03:22 03 10:03:22 3 10:03:22 10:03 as Tuesday, January 30, 2018 code x.ToString("MMMM") x.ToString("dd") x.ToString("MMM") x.ToString("MMM/YYYY") x.ToString("ss") x.ToString("mm") x.ToString("m") x.ToString("hh:mm") USING DIALOG CONTROLS Show Dialogs (MessageBox.Show()) Open File Dialog Control Save File Dialog Control Color Dialog Control Font Dialog Control Print Dialog Control Where to check and prompt (upon closing the form) Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing If flag = True Then If MessageBox.Show("Save current changes?", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then SaveTextFile() End If End If End sub AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:33 OF 46

  34. Question What is the screen displayed for this code MessageBox.Show("Can't find the drive", "Attention", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation) Response = ? Or write the code to display the following dialog? AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:34 OF 46

  35. MessageBox.Show("data deleted", "report", MessageBoxButtons.OK, MessageBoxIcon.Information) OPEN FILE DIALOG CONTROL PROPERTIES PROPERTY CheckFileExists True/False CheckPathExists True/False FileName Read or assign file name Filter Type of file to open FilterIndex Default filtered group to be selected InitialDirectory Initial directory to start on open Restoredirectory True/false Title A title appear on to bar of open dialog MultiSelect True/false CODING PROPERTIES We can change any value also by code Assume OpenFileDialog Control Name is O1 It contains preset properties (properties to be set before calling it) and property after calling to get the file name selected. PRESET PROPERTIES OD1.CheckFileExists= true It will check whether the file name selected is valid or not, if not, it will give us a notice. OD1.ChechPathExists= true: It will check whether the path selected is valid or not, if not, it will give us a notice Set file name by default - code OD1.FileName= "Sales": it makes the selected file name to be opened by default as Sales. If it is empty, the default file name will be empty; user should click on the file name to select it AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:35 OF 46

  36. File name property could be used before calling the dialog, to set the default file name to be opened, and also after calling the dialog to get the selected file name. Read selected file - code F = OD1.FileName:this will put the full file name in variable f. to be used later for opening or any other action OD1.Filter = "": display different file types available to open in 2 values [Description|Type] as follows OD1.Filter = "Text Files|*.txt" OD1.Filter = "Text Files|*.txt|Pictures|*.jpg" OD1.Filter = "Text Files|*.txt|Pictures|*.jpg|csv|*.csv" OD1.Filter = "Text Files|*.txt|Pictures|*.jpg|csv|*.csv|Excel|*.xlsx" If we put code in the last line which one is the default? OD1.FilterIndex = 1 means Text Files is the default Type selected OD1.FilterIndex = 2 means Pictures is the default Type selected OD1.FilterIndex = 3 means csv is the default Type selected O1.InitialDirectory = "D:\Inbox\" This means the first time we open, it goes by default to D:\Inbox\ to open files in it OD1.RestoreDirectory = true: it means it remembers the last directory used and goes to it OD1.RestoreDirectory= false: it means it doesn’t remember the last directory used and goes to it; it goes to initial directory instead. Note: for RestoreDirectory to take effect, Initialdirectory should not set OD1.MultiSelect=true/false: if true allows us to select multiple files when opening, if false it allows us to select only one file. OD1.Title =: a title appears on the top of the dialog SAVE FILE DIALOG CONTROL PROPERTIES This is the same as Open file dialog box, except that the property of Multiselectdoesn’t exist in save. It serves as save and save as. In addition it has a property DefaultExt :which means if you set it to txt, then assigning a file name to memo, will be saved as memo.txt, if you write the file name as memo.txt it will be saved as memo.txt FONT DIALOG CONTROL PROPERTIES The font dialog box gives us the possibility of selecting the font name, font size, font color and effects (Underline and strikethrough) and use the selected properties to be set for a text property AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:36 OF 46

  37. Use FD1 to denote the name of FontDialog control FD1.ShowColor =True/False: if we want to change font and not interested in font color, use FD1.showcolor = false, if we want the colors to be used for selected font use FD1.showcolor = true. FD1.ShowEffects = True/False ‘Show/Hide strikethrough and underline properties for a selected font Note : if showeffects = false and showcolor=true, color will not shown because it is considered as effect How to set the properties of a of a text box, as selected properties of the Font Dialog? We use T1.font = FD1.font to set the font name, size and effects T1.forecolor = FD1.color to set the font color COLOR DIALOG CONTROL PROPERTIES A color dialog control allows us to pick a selected color from color palette. Use CD1 to denote ColorDialog1 If we want the default picked color as red when opened, we use CD1.color = color.red If we want to show the full color palette use CD1.fullOpen = True How to get and use selected color, for T1 text box for example We can set the Forecolor of the textbox as T1.ForeColor = CD1.Color Or we can set the Back Ground Color of T1 as T1.BackColor = CD1.color PRINT DIALOG CONTROL Just call it. HOWTO CALL DIALOGS. ColorDialog1.ShowDialog() and So on for other controls But it is not sufficient because we don’t know if user choose a color and pressed OK or cancel. How to detect user selection ? Dim Response as integer Response = ColorDialog1.ShowDialog() AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:37 OF 46

  38. If response = DialogResult.OKthen If response = DialogResult.Cancel then If response = DialogResult.Yes then If response = DialogResult.No then If response = DialogResult.Retry then If response = DialogResult.Abort then If response = DialogResult.Ignore L LI IS ST T B BO OX XE ES S & &C CO OM MB BO O B BO OX XE ES S CoboBoxes ListBoxes W WH HA AT T I IS S A A C CO OM MB BO O B BO OX X : : Combo box means compound Box, it serves as CheckBox When it is preferred to be used? For Gender Male Female, we could use either checkbox or combobox. or But, if you want user to select among large different choices as his country, it is not possible to use checkbox, we must use ComboBox instead. Both enable us to select one value. How to of a Combo (assume its name is C1) Code task C1.Items.clear() clear/delete the contents C1.Items.Add("Jerusalem") Add a value to the combo AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:38 OF 46

  39. Set the default value C1.Text = "Jenin" C1.Items.Remove("Tulkarem") Remove/delete a value C1.Items.IndexOf("Jenin") C1.Items.RemoveAt(4) C1.Items.Insert(3, "HHH") Position of a value starting from zero Remove 5th element Insert a value at specified index, provided that sorted =false What is the List Box? It is a list that can show multiple elements at the same time, it can allow us to select one or multiple values. SelectionMode property None, one, multiSimple, MultiExtended In code we could use L1.SelectionMode = SelectionMode.one L1.SelectionMode = SelectionMode.MultiExtended If we have 2 lists L1 and L2 To add the items of L1 to L2 L2.Items.AddRange(L1.Items) To remove selected item from L2 Dim s as string = L2.Text L2.Items.Remove(s) AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:39 OF 46

  40. M MI IS SC CE EL LL LA AN NE EO OU US S T TO OP PI IC CS S Current application path (absolute and Relative) File Exist Using Rich text Format control Startup Form Try Catch Using with keyword Using SaveSetting & GetSetting Evaluating String expressions into values Using Windows API calls Using font object(New) C CU UR RR RE EN NT T F FI IL LE E P PA AT TH H If we have a file name Memo.txt saved in c:\documents\memos and want to open it there exist 3 different methods to get the full path and file name 1-Use absolute path-name as Dim F as string F = "C:\documents\memos\Memo1.txt" 2-We can Get the file name by using Open Dialog control, if we have an OpenFileDialog Name O1 then we can use Dim F as string If O1.ShowDialog() = DialogResult.OK then F = O1.FileName End If 1-Use Relative Path-name as If you know that the file exist in the same place the vb.nex executable file, you can get it. If the file exist in the current running application file, you can get the current running path, and add the file name to it Dim F as string F =AppDomain.CurrentDomain.BaseDirectory() & "Memo1.txt" AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:40 OF 46

  41. F FI IL LE E E EX XI IS ST T Sometimes it is necessary to check if the file name specified is valid or not. Why? Because when you use it, it might be deleted before opening it, therefore, you are trying to open a file that does not exist. How to solve this issue, by checking if the file exist, continue, if not, display a message. System.IO.File.Exists(F) If it’s value is true, then the file exist If it’s value is false, the file doesn’t exist U US SI IN NG G R RI IC CH H T TE EX XT T F FO OR RM MA AT T C CO ON NT TR RO OL L RTF stands for Rich Text Format, which means the format of a text is rich with font size, type, effects and colors. You can save a file from Microsoft word (save as, RTF type) In VB.net we can open the file using Rich Text Box Note: for Not RTF (called Plain Text) we use TextBox or rtf Drag an RTF control on a form, Name it as RT1. To open the file and put its contents in RT1 RT1.LoadFile("C:\Users\intro.rtf",RichTextBoxStreamType.RichText) You can open it in 3 different modes RichTextBoxStreamType.RichText RichTextBoxStreamType.PlainText RichTextBoxStreamType.UnicodePlainText (Multilingual) S ST TA AR RT TU UP P F FO OR RM M In a visual basic project, the default startup form is the first form added to project which is Form1. We can change the startup form in 2 different methods. As it is As text file As text File AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:41 OF 46

  42. 1-From the main menu, select project, then project properties, from the dropdown for startup form, selects the form you want it as startup. 2-You can add a module, and write a code in sub main, to write the code to show the startup form manually, of course in the project properties, you have to select from the dropdown sub main as startup In the module add the following code, if you want the startup form to be fMain rather than f1 Sub Main() fMain.showDialog() End Sub T TR RY Y … …C CA AT TC CH H … …E EN ND D T TR RY Y Try catch is used to catch errors and handle them. How to open a Rich Text Format File ? Dim F As String F = "C:\Users\intro.rtf" RT1.LoadFile(F, RichTextBoxStreamType.PlainText) What will happen if the file doesn’t exist The application will crash and exit/quit suddenly We want to prevent the application from exiting, and display a message to the user that the operation failed, continue running The code is written between try and catch Any error is handled between catch and end try Try Dim F As String F = "C:\Users\intro.txt" RT1.LoadFile(F, RichTextBoxStreamType.PlainText) Catch ex As Exception MessageBox.Show(ex.Message) Finally End Try AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:42 OF 46

  43. U US SI IN NG G W WI IT TH H Sometimes you need to write code for the same control and change several properties, it is useful to use with keyword to make it simpler For example if we want to set the properties of a text box T1 as follows T1.text ="welcome to vb.net" T1.Forecolor = color.red T1.MaxLength = 22 T1.multiline = false T1.TabStop = true We can use with as follows With T1 .Forecolor = color.red .MaxLength = 22 .multiline = false .TabStop = true End with Using SaveSetting & Getsetting Each application has some presetting values used as default values, if user changes them, they will be saved. These are global variables and they are saved inside the windows registry. How to see the windows registry From windows, select run then type- regedit Values are saved in HKEY_CURRENT-USER, then software, then Microsoft, then VB and VBA Program Settings. Because many applications can save many variables having many values, it is organized inside VB and VBA Program Settings in a tree structure as follows: All variables related to a specific application are saved inside ApplicationName Node Each related variables are located inside a node called section AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:43 OF 46

  44. Each variable is assigned a name(key) and value(setting) For example, if we have an application named Payroll, we want to save use name and password, PhoneNo, Email,website. Application Name Variable name (Key) Section Variable Value (Setting) Username dwikat Security Password PhoneNo P@ssw0rd 09232110 Payroll General Email dwikatmo@gmail.com website www.eschool.ps SaveSetting("Payroll", "Security", "UserName", txtUserName.Text) SaveSetting("Payroll", "Security", "Password", txtPassword.Text) SaveSetting("Payroll", "General", "PhoneNo", txtPhoneNo.Text) SaveSetting("Payroll", "General", "Email", txtEmail.Text) SaveSetting("Payroll", "General", "WebSite", txtWebSite.Text) On the contrary, if we want to read their values, and put it in a proper text box txtUserName.Text = GetSetting ("Payroll", "Security", "UserName", DefaultValue) DefaultValue: is an optional given default value to use if the value doesn’t exist. Naturally, when you use the application first time, all values will be empty, default values could be used. Write a code to save a value of salman (inside Registry), in a variable(key) FirstName, in a section Info for application name Zajel SaveSetting("Zajel", "Info", "FirstName", "Ahmad") Write a code to retrieve the previous value and put it inside a string variable s, set it to Anonymous if value not exist S= GetSetting("Zajel", "Info", "FirstName","Anonymous") AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:44 OF 46

  45. Evaluating String expressions into values Dim S as string S = ("5+3") Dim x as integer x = New DataTable().Compute(s, Nothing) Using Windows API calls Private Const EWX_LogOff = 0 Private Const EWX_SHUTDOWN = 1 Private Const EWX_REBOOT = 2 Private Const EWX_FORCE = 4 Public Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long Calling the API Function Call ExitWindowsEx(EWX_FORCE, &HFFFFFFFF) U US SI IN NG G V VI IS SU UA AL L B BA AS SI IC C F FO OR R A AP PP PL LI IC CA AT TI IO ON NS S Using VBA (Visual Basic for applications) VBA means using visual Basic to enhance and automate Microsoft Office Applications as Excel, Word, PowerPoint, Outlook and other applications like Access. AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:45 OF 46

  46. U US SI IN NG G W Dim sapi sapi = CreateObject("sapi.spvoice") sapi.speak(T1.Text) U US SI IN NG G E EX XC CE EL L F FR RO OM M V VB B. .N NE ET T We can open Excel as Object, use it in code, send data to excel sheets and more and more WI IN ND DO OW WS S T TE EX XT T T TO O S SP PE EE EC CH H AUTHOR:MOHAMMED ABDEL KHALEQ DWIKATEMAIL:dwikatmo@gmail.com TOPIC:VISUAL BASIC II/FORMS DATE:24/01/2019PAGE:46 OF 46

More Related