P. 1
Visual Basic Tutorial

Visual Basic Tutorial

|Views: 861|Likes:

More info:

Published by: Zaeni Marjiyanto, A.md on Jan 18, 2010
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as DOCX, PDF, TXT or read online from Scribd
See more
See less





Dated: 2004-08-12 y y y y y y y y y y y y y y y y y y

Introduction Visual Basic Objects Let The Games Begin Visual Basic's IDE Setting up the Forms Intrinsic Controls Working with Combo Box Events Let's Get Started with the Code Controlling Program Flow Conditional Operators Using If.....Then.....Else Statements with Operators Select Case Looping Function in Visual Basic. Arrays Working with Files Visual Basic and the Databases.

VISUAL BASIC is one of the easiest programming tool to master. With some basic guidance, anybody could come up with a nice little windows-based program within a short time, age is not the limit. However, do not ever think that Visual Basic can only build simple programs, you could actually develop very advance and powerful applications. Indeed, Visual Basic 6.0 even allows you to develop web applications. Nevertheless, advance programming is temporarily out of the scope of this web site, if you are still interested, please refer to some of the links provided in this page. VISUAL BASIC is a high level programming language evolved from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. It is a fairly easy programming language to learn. The codes look a bit like English Language. Different software companies produced different version of BASIC, such as Microsoft QBASIC, QUICKBASIC, GWBASIC ,IBM BASICA and so on. Visual Basic (VB) is a beginner programming language for authoring Windows©-based software. In the past, VB was known as the language of the hobbyist, but since version 5.0,

professional programmers have taken notice of the potential of VB. Applications written with VB will only run on computers with a minimum Windows 95. .

Visual Basic Objects
Program code is written by referring to objects. In the real world, an object is basically any person, place, or thing. You might also consider non-visible things as objects. For instance, oxygen cannot be physically seen, but can be represented by chemical diagrams. Visual Basic follows this same theory of objects; some visible, some not visible. Objects have characteristics, or attributes. We call these Properties in VB. Objects do things and perform actions. We call these the object's Methods. When an object performs an action, sometimes it produces a tangible result. This is a special type of Method called a Function. Methods and Functions of an object may require some specific information peculiar to the situation. These individual pieces of information are called Arguments, or sometimes parameters. Code written with VB does not always use an object's properties, methods, and functions. VB has done much of the work for you by supplying Global Statements. The syntax (correct way to write code) varies from statement to statement.

Let The Games Begin...
VISUAL BASIC is a VISUAL and events driven Programming Language. These are the main divergence from the old BASIC. In BASIC, programming is done in a text-only environment and the program is executed sequentially. In VISUAL BASIC, programming is done in a graphical environment. Because users may click on a certain object randomly, so each object has to be programmed independently to be able to response to those actions (events). Therefore, a VISUAL BASIC Program is made up of many subprograms, each has its own program codes, and each can be executed independently and at the same time each can be linked together in one way or another. As a beginner starting a new VB project, always select Standard EXE. ActiveX type projects are advanced and require a broad understanding of the language. With IIS and DHTML applications (which are new to VB 6.0), you can create programs designed for the Internet. Now right there in front of you is a form. A form is simply a window that you design. You'll draw controls on the form to create a Graphical User Interface (GUI). Forms and controls are both objects. Since controls are part of a form, you could say that a form is the parent object. The importance of the parent/child relationship between objects becomes more apparent as you learn more about programming.

A project (.vbp file) is an "application on the drawing board" and actually is just a straight text file containing information about your project as a whole and where your forms and code modules are located on your computer.

Visual Basic's IDE
On start up, Visual Basic 6.0 will display the following dialog box as shown in the first figure. You can choose to start a new project, open an existing project or select a list of recently opened programs. A project is a collection of files that make up your application. There are various types of applications we could create, however, we shall concentrate on creating Standard EXE programs (EXE means executable program). Now, click on the Standard EXE icon to go into the actual VB programming environment.

In the second below figure 2, the Visual Basic Environment consists of the The Blank Form window which you can design your application's interface. The Project window displays the files that are created in your application. The Properties window which displays the properties of various controls and objects that are created in your applications. It also includes a Toolbox that consists of all the controls essential for developing a VB Application. Controls are tools such as boxes, buttons, labels and other objects draw on a form to get input or display output. They also add visual appeal.

The Toolbox In order to draw controls, you must have the toolbox visible. You do this by clicking the toolbox icon on the toolbar or selecting Toolbox from the View menu. Click on the desired control and draw it on a form by dragging the mouse from the upper left to the lower right positions of where you want the control to be on the form. Also, double-clicking on the control in the toolbox will place a default sized control in the center of the form. Afterwards, you can drag the control to any new position on the form. The toolbox pictured is all the intrinsic controls available. VB also comes with custom controls (OCX's) which can be added to the toolbox by going to Project/Components. You'll find some very useful custom controls here, such as the ToolBar, StatusBar, RichTextBox, DBGrid (Data Bound Grid), and many others.

Setting Up The Forms
Before drawing any controls on a Form, you should do the following: Name the form and save it A Form has a name (which is how you refer to it in code) and a file name with an .frm extension. An .frm file is actually a straight text file which contains instructions that VB uses to create the Form. Load an .frm file into any text editor if you want to see these instructions. I usually right click on the Form in Project Explorer and select "Save Form1 As", give the file a name and save it, and then immediately go to the Properties Window and give the Form a descriptive name with an "frm" prefix.

Decide what kind of border to use By default, your Form will have the familiar blue title bar on top, a "Form" icon, a "Form1" title, minimize, maximize, and close buttons, (referred to as the Control Box), and be sizable at run time. Any of this can be changed while designing the Form, but only the title (Caption property) and the icon (Icon property) can be changed at run time. BorderStyle property

y y y y y

0 - None No border, title, icon, or control box. The form will not be sizable, or able to be moved by the user. You are responsible for writing code to close the Form at run time. A common setting for games. 1 - Fixed Single Same as a default form, but the user cannot resize it. 2 - Sizable Default 3 - Fixed Dialog No minimize or maximize buttons, no Icon, and not sizable by the user. This setting is used for specialized dialog boxes. 4 - Fixed ToolWindow A Tool Window has a slimmer title bar, and no minimize or maximize buttons. Use this setting as a utility form, such as a toolbox. 4 - Sizable ToolWindow Same as above but able to be resized by the user.

MinButton, MaxButton, and ControlBox properties These three properties can be set to True or False. Setting ControlBox to False will remove all three buttons. Setting MinButton or MaxButton to False will not totally remove the button, but rather just gray it out so it cannot be used. Setting both MinButton and MaxButton to False will remove both buttons. You cannot gray out the close button (the 'x') without some help from API calls and you can only remove it by removing the entire Control Box. WindowState property Set this property at design time to indicate how the Form will be displayed initially.
y y y

0 - Normal The Form will display according to the size and location you decided at design time. In most cases, you'll use this setting which is also the default. 1 - Minimized The Form will start up minimized as an icon in the Windows Taskbar. 2 - Maximized The Form will run full screen, but this may not be a good idea if you're eventually going to run your program on different machines, due to the different screen sizes. You might think your controls are nicely placed until you run the Form on a different computer with a larger screen size and find a lot of empty space or on a smaller screen size and the whole Form doesn't seem to be there.

StartUpPosition property If your Form is not maximized, you'll need to place it in an appropriate place on the screen. You can do this with the Form Layout Window or set the StartUpPosition property.

y y y y

0 - Manual You'll set the Left and Top properties of the Form in the Form's Load event. 1 - CenterOwner The form will be centered on the form which owns it. 2 - CenterScreen The Form will run centered on the screen. A most pleasing effect in my opinion. 3 - Windows Default This is the default setting. You're putting the decision into the hands of Windows, which can be unpredictable.

Moveable property By default, the Moveable property is set to True, meaning users will be able to move your Forms by dragging on the title bar. Set this property to False to create a non-moveable Form. This won't affect whether or not the Form can resized. Caption property This is the title of your Form. It will appear on the left side of the title bar next to the Icon. You can set this property dynamically, (which simply means at run time), if your Form has multiple purposes and needs different titles at different times. Icon property Set this property to an icon picture file if you don't like the "Form" icon. Actually, using the default form icon is somewhat non-professional. The icon can be changed at run time by setting the property with the LoadPicture function or setting it to a picture which is already a property of another Form or Control with a Picture property. The standard Windows icon is also available by going to a Form's Properties Window, highlighting the (Icon) text and pressing the delete key. Picture property Set this property to any valid picture file to set a background for your Form. The picture file should be of the correct size, you cannot stretch, shrink, center, or tile it without some help from Bit Block Transfer See Image control for a list of valid picture file formats. .

Intrinsic Control
Command Button The most familiar of all controls is the Command Button. The Command Button can be of 2 styles- graphical and standard. The standard Command Button displays text describing what the button does, while the graphical style can display a picture, text, or both. You cannot insert a picture or change the background color (BackColor) until you set the Style property to 1Graphical. The Style property is read-only at run-time, therefore you must decide which style to use at design-time.

Often, you'd want a Command Button to be the default button of the form which means if the user presses the enter key, the code in the button's Click event will run. Commonly, you would set the button's Default property to True if that button accessed the most common function of that form. On the other hand, you can set the Cancel property to True. This would run the button's code if the user pressed the escape key. These two properties would be perfect for "OK" and "Cancel" buttons. Another way to run the code in a Command Button's Click Event is to set the Value property to True. This will only work at run-time, you won't find this property in the Properties Window.
cmdEnter.Value = True

Even another way to run a button's Click Event is to set up an access key. This allows to user to hold the ALT key and press one letter in place of actually clicking the button. Do this by adding an ampersand (&) in front of the desired letter while typing the Caption property. That letter will be underlined on the button to indicate that an access key is active.

Text Box The Text Box is a heavily used control which allows users to enter and edit text. If you want a control which just displays text, then use a Label. You can only use one style of text in a Text Box. For instance, half bold and half italics is not possible. You'll need a RichTextBox control for that. The Text property holds whatever text is in the control. Use the Alignment property to left, right, or center justify the text. The Locked property can be useful for switching between an editable and a not editable Text Box. Setting the MaxLength property to anything other than 0 will limit the number of characters which can be entered. The PasswordChar property is commonly set to an asterisk (*) to have the Text Box serve as a field for entering a password. If you desire, the Text Box can have scroll bars horizontally, vertically, or both. Set the Multiline property to True if you want your Text Box to automatically word wrap. The SelText property holds whatever text is highlighted (selected); this is most useful when adding cut, copy, and paste functionality to your program. The SelLength property will tell you how many characters are highlighted. The SelStart property tells you where highlighted text begins, or, if no text is highlighted, it tells where the insertion point is.

In this Text Box, the value of SelText is "score and seven", the value of SelLength is 15, and the value of SelStart is 5 (meaning there are 5 un-highlighted characters before the SelText).

If a Text Box loses the focus, any highlighting will disappear and then only return when the Text Box gains the focus again. But that is only the default behavior; set the HideSelection property to False to keep the highlighted text as is no matter what control is active. Label A Label's main purpose is to display some descriptive text. Like a Text Box, you can have the text left, right, or center justified. You can also have the Label automatically size itself to fit its Caption by setting AutoSize to True. A WordWrap property is also available. Having the Label's Backcolor match that of it's container (forms, picture boxes, and frames are containers) is done by setting BackStyle to Transparent. Use BackColor only if you want different colors. Like Command Buttons and some other controls, Labels can have access keys by using an ampersand(&) within the Caption. Normally, an access key runs the code in that control's Click event, but an access key in a Label merely sets the focus to the next control in the tab order. To actually display an ampersand in the Label, use a double ampersand. For instance, to display "Stars & Stripes" in a Label, you would need to use "Stars && Stripes". Or, the UseMnemonic property can be set to False to "turn off" the access key, thereby displaying ampersands. List Box: A List Box presents a list of choices to the user. If the list items are known at design time, you can add them in the Properties Window; Click list, and a small edit area appears. Type the first item and then hold the Ctrl key while pressing enter in order to type another list item. Users are familiar with double clicking list items to make a selection, so most of the time you'll be writing code for the List Box's DblClick event. Setting sorted to True will automatically alphabetize the list. To display check boxes next to the list items, set the Style property to 1-checkbox. A separate page is devoted to List Boxes: Combo Box A Combo Box is a combination List Box/Text Box. Usually, you'd use this control when space is at a premium and a List Box just won't do. A separate page is devoted to ComboBoxes:
Working With Combo Box

Most of what you already know about ListBoxes will apply to a ComboBox. Items are added, removed and cleared with the AddItem, RemoveItem, and Clear methods. List, ListIndex, ListCount, NewIndex, and ItemData properties all the work the same way, however ComboBoxes cannot have multiple columns or handle multiple selections. The Style property is read only. That means you must decide which style to use at design time and an error will occur if you try to set the value of the property at run time. There are three styles to consider.




The Simple style appears like you've drawn a TextBox just over a ListBox. If the user highlights (clicks) one of the items in the ListBox portion, the text automatically appears in the TextBox portion. Alternatively, the user can elect to input their own text directly into the TextBox. Either way, the Text property will hold the user's selection. This is the only style of ComboBox which will respond to a double click and the double click must come from the ListBox portion of the control. The Dropdown Combo is probably the most used style. This style can be drawn as wide as it needs to be but it's Height is limited to the space needed for one line of text. (This is governed by the FontSize). By default, the Text property will be set to "Combo1", so you should set it's initial value in the Properties Windows or in code (Form_Load event). The user will either select an item from the drop-down list or type in their own. Your first thought might be to use the Change event to respond to the user selecting an item, but oddly enough the Click event handles this. The Dropdown List does not take user input. The Text property is read-only with this style, unless you assign a string in code which is already a list item.

Private Sub Form_Load( ) cboList.Text = cboList.List(3) End Sub

Other than this one difference, the Dropdown List style works identically to the Dropdown Combo. Since the Dropdown Combo and Simple styles are part TextBox, you can use some of the TextBox properties like Locked, SelText, SelLength, and SelStart.

Visual Basic programs are event-driven, meaning code will run only in response to events. Each object has its own set of events, but many are common to all objects. Events can be triggered by the user, such as clicking a button, triggered by your own code, and even by the actions of your program, such as start-up and shut-down. Change The most common use for this event is with a TextBox, but it does occur in other controls, like ComboBox, Label and some others. This event fires when the contents (most often the text) of a control have changed, so for every key a user types, you can check for valid data entry, or limit what can be entered. Click The most common event. Users expect something to happen when they click things, so you'll be writing a lot of code for this event. Just about every control has a click event. Double Click Abbreviated DblClick in a code window. Keep in mind that DblClick triggers two Click events, so don't write conflicting code in both events.

DragDrop Triggered at the completion of a drag and drop operation. Or in other words, when the user releases the mouse after dragging an object to another location. DragOver Triggered constantly as an object is being dragged. Use this event to control or limit the drag and drop operation. Don't write any long drawn out code here. GotFocus and LostFocus GotFocus occurs when the focus has switched to an object. This can be triggered by the user clicking on it, or tabbing to it. Since only one object can have the focus, another control will receive a LostFocus event at the same time. KeyDown, KeyUp, and KeyPress Use these events to capture what the user is typing. More often, you'll use KeyDown, but you may run into a situation where you need to respond to releasing of a key. These two events can detect just about any key typed including the state (up or down) of the Ctrl, Alt, and Shift keys. To check for standard letter and number keys, use KeyPress, just remember one press of a key triggers all three events. MouseDown, MouseMove, and MouseUp Similar to the Key events above, these events are triggered by mouse actions. MouseMove can be triggered several times per second, so let's not write complex calculations in this event. Scroll If an object has scroll bars (ListBox, ComboBox, etc.) this event fires when the user clicks the up or down arrow or drags the position indicator. This event does not apply to a TextBox with scroll bars. Form Events Several Form events will fire starting with the moment of creation. Each has its own purpose and triggers in a certain order. When the Form is first created, an Initialize event will occur, followed by Load, Resize, and Paint. Upon destruction of the Form, events triggered are QueryUnload, Unload, and Terminate. Initialize This event occurs only once when the Form is created. It will not fire again unless the Form is Unloaded and Loaded again.

Load Occurs when a Form is loaded. This event can only be fired again if the form is unloaded and loaded again. If a Form loses the focus (thereby losing it's status as the ActiveForm) and then becomes active again, an Activate event will fire. Resize Even though no physical resizing has occurred, this event triggers after Load. It will also be set off by minimizing, maximizing, restoring, and resizing. Paint This event fires for the purpose of drawing graphics on the form. Activate and Deactivate If a form becomes the ActiveForm (has the focus), Activate will fire, followed by GotFocus. If another form becomes active, the LostFocus event will occur, followed by Deactivate. However, GotFocus and LostFocus will only trigger when the form has no enabled controls. QueryUnload This event is used for checking to make sure it's OK to shut down. In this event, you can actually stop shut-down and even check if the user is trying to shut-down, your code invoked shut-down, or if Windows itself is responsible. QueryUnload has two built-in parameters for dealing with these situations- Cancel and UnloadMode.
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer If MsgBox("Are you sure you want to shut down?", vbYesNoCancel) <> vbYes Then Cancel = True End If End Sub

Cancel = True means "cancel the unloading of this form". You would probably check some program condition before deciding to set Cancel to True, or you could use a simple message like the above example. Unload After having passed through QueryUnload, this event fires and any code which aids in having that form out of memory is processed.

Lets Get Started with the Code

CSS Selectors can provide the Author extended control over how their Lists are formatted Now we shall attempt to write the codes for the cylinder program.

Now, doubleclick on the O.K button and enter the codes between Private Sub OK_Click( ) and End Sub Private Sub OK_Click( ) r = Val(radius.Text) h = Val(hght.Text) pi = 22 / 7 v = pi * (r ^ 2) * h volume.Text= Str$(v) End Sub when you run the program , you should be able to see the interface as shown above. if you enter a value each in the radius box and the height box, then click OK, the value of the Volume will be displayed in the volume box. I shall attempt to explain the above source program to newcomers in Visual Basic( If you are a veteran, you can skip this part) . Let me describe the steps using pseudocodes as follows: Procedure for clicking the OK button to calculate the volume of cylinder get the value of r from the radius text box get the value of h from the height text box assign a constant value 22/7 to pi calculate the volume using formula output the results to the Volume text box

End of Procedure

The syntax radius.Text consists of two parts, radius is the name of text box while Text is the textual contents of the text box. Generally, the syntax is: Object.Property In our example, the objects are radius, hght and volume, each having text as their property.Object and property is separated by a period(or dot).The contents of a text box can only be displayed in textual form, or in programming term,as string. To convert the contents of a text box to a numeric value so that mathematical operations can be performed , you have to use the function Val. Finally, In order to display the results in a text box, we have to perform the reverse procedure, that is, to convert the numeric value back to the textual form, using the function Str$. I shall also explain the syntax that defines the sub procedure Private Sub OK_click. Private Sub here means that the parameters , values and formulas that are used here belong only to the OK subprocedure(an object by itself).They cannot be used by other sub procedures or modules. OK_Click defines what kind of action the subprocedure OK will response .Here, the action is mouse click. There are other kind of actions like keypress, keyup, keydown and etc that I am going to due with in other lessons.

Controlling Program Flow
Conditional Operators To control the VB program flow, we can use various conditional operators. Basically, they resemble mathematical operators. Conditional operators are very powerful tools, they let the VB program compare data values and then decide what action to take, whether to execute a program or terminate the program and etc. These operators are shown below

Operator = > < >= <= <>

Meaning Equal to More than Less Than More than and equal Less than and equal Not Equal to

You can also compare strings with the above operators. However, there are certain rules to follows: Upper case letters are less than lowercase letters, "A"<"B"<"C"<"D".......<"Z" and number are less than letters.

Logical Operators In addition to conditional operators, there are a few logical operators which offer added power to the VB programs. There are shown Below Operator Meaning And Both sides must be true or One side or other must be true Xor One side or other must be true but not both Not Negates truth Using If.....Then.....Else Statements with Opreators To effectively control the VB program flow, we shall use If...Then...Else statement together with the conditonal operators and logical operators. The general format for the if...then...else statement is If conditions Then VB expressions Else VB expressions End If any If..Then..Else statement must end with End If. Sometime it is not necessary to use Else. Example: Private Sub OK_Click() firstnum = Val(usernum1.Text) secondnum = Val(usernum2.Text) total = Val(sum.Text) If total = firstnum + secondnum And Val(sum.Text) <> 0 Then correct.Visible = True wrong.Visible = False Else correct.Visible = False wrong.Visible = True End If End Sub

Select Case

If you have a lot of conditional statements, using If..Then..Else could be very messy. For multiple conditional statements, it is better to use Select Case The format is : Select Case expression Case value1 Block of one or more VB statements Case value2 Block of one or more VB Statements Case value3 Block of one or more VB statements Case value4 . . . Case Else Block of one or more VB Statements End Select The data type specified in expression must match that of Case values.

Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called looping . Do Loop The format are a) Do While condition Block of one or more VB statements Loop b) Do Block of one or more VB statements Loop While condition


Do Until condition Block of one or more VB statements Loop Do Block of one or more VB statements Loop Until condition


Example Do while counter <=1000 num.Text=counter counter =counter+1 Loop The above example will keep on adding until counter >1000. The above example can be rewritten as Do num.Text=counter counter=counter+1 Loop until counter>1000 For Next Loop The format is: For counter=startNumber to endNumber (Step increment) One or more VB statements Next Example: (a) For counter=1 to 10 display.Text=counter Next


For counter=1 to 1000 step 10 counter=counter+1 Next


For counter=1000 to 5 step -5 counter=counter-10 Next

Functions In Visual Basic
Creating Your Own Functions The general format of a function is as follows: Public Function functionName (Arg As dataType,..........) As dataType or Private Function functionName (Arg As dataType,..........) As dataType Public indicates that the function is applicable to the whole program and Private indicates that the function is only applicable to a certain module or procedure. Example In this example, a user can calculate future value of a certain amount of money he has today based on the interest rate and the number of years from now (supposing he will invest this amount of money somewhere). The calculation is based on the compound interest rate.

Public Function FV(PV As Variant, i As Variant, n As Variant) As Variant 'Formula to calculate Future Value(FV) 'PV denotes Present Value FV = PV * (1 + i / 100) ^ n End Function Private Sub compute_Click() 'This procedure will calculate Future Value Dim FutureVal As Variant Dim PresentVal As Variant Dim interest As Variant Dim period As Variant PresentVal = PV.Text interest = rate.Text period = years.Text FutureVal = FV(PresentVal, interest, period) MsgBox ("The Future Value is " & FutureVal) End Sub Example The following program will automatically compute examination grades based on the marks that a student obtained.

Public Function grade(mark As Variant) As String Select Case mark Case Is >= 80 grade = "A" Case Is >= 70 grade = "B" Case Is >= 60 grade = "C" Case Is >= 50 grade = "D" Case Is >= 40 grade = "E" Case Else grade = "F" End Select End Function Private Sub compute_Click() grading.Caption = grade(mark)

End Sub Private Sub End_Click() End End Sub

Arrays in VB
Introduction to Arrays By definition, an array is a list of variables, all with the same data type and name. When we work with a single item, we only need to use one variable. However, if we have a list of items which are of similar type to deal with, we need to declare an array of variables instead of using a variable for each item. For example, if we need to enter one hundred names, instead of declaring one hundred different variables, we need to declare only one array. We differentiate each item in the array by using subscript, the index value of each item, for example name(1), name(2),name(3) .......etc. Declaring Arrays We could use Public or Dim statement to declare an array just as the way we declare a single variable. The Public statement declares an array that can be used throughout an application while the Dim statement declare an array that could be used only in a local procedure. The general format to declare an array is as follow: Dim arrayName(subs) as dataType where subs indicates the last subscript in the array. Example Dim CusName(10) as String will declare an array that consists of 10 elements if the statement Option Base 1 appear in the declaration area, starting from CusName(1) to CusName(10). Otherwise, there will be 11 elements in the array starting from CusName(0) through to CusName(10) Example Dim Count(100 to 500) as Integer declares an array that consists of the first element starting from Count(100) and ends at Count(500) Sample Programs (i)

The Interface

The codes Dim studentName(10) As String Dim num As Integer Private Sub addName() For num = 1 To 10 studentName(num) = InputBox("Enter the student name", "Enter Name", "", 1500, 4500) If studentName(num) <> "" Then Form1.Print studentName(num) Else End End If Next End Sub Private Sub Exit_Click() End End Sub

Private Sub Start_Click() Form1.Cls addName End Sub The above program accepts data entry through an input box and displays the entries in the form itself. As you can see, this program will only allows a user to enter 10 names each time he click on the start button. (ii) The Interface

The Codes Dim studentName(10) As String Dim num As Integer Private Sub addName( ) For num = 1 To 10 studentName(num) = InputBox("Enter the student name") List1.AddItem studentName(num) Next End Sub Private Sub Start_Click() addName

End Sub The above program accepts data entries through an InputBox and displays the items in a list box. Working With Files Introduction Up until we are only creating programs that could accept data at runtime, when a program is terminated, the data also disappear. Is it possible to save data accepted by a VB program into a storage device, such as a hardisk or diskette, or even CDRW? The answer is possible. Is this section, we will learn how to create files by writing them into a storage device and then retrieve the data by reading the contents of the files using customized VB programs. Creating files To create a file , use the following command Open "fileName" For Output As #fileNumber Each file created must have a file name and a file number for identification. As for file name, you must also specify the path where the file will reside. For example Open "c:\My Documents\sample.txt" For Output As #1 will create a text file by the name of sample.txt in the My Document folder. The accompany file number is 1. If you wish to create and save the file in A drive, simply change the path, as follows" Open "A:\sample.txt" For Output As #1 If you wish to create a HTML file , simple change the extension to .html Open "c:\My Documents\sample.html" For Output As # 2 Sample Program : Creating a text file Private Sub create_Click() Dim intMsg As String Dim StudentName As String Open "c:\My Documents\sample.txt" For Output As #1 intMsg = MsgBox("File sample.txt opened") StudentName = InputBox("Enter the student Name")

Print #1, StudentName intMsg = MsgBox("Writing a" & StudentName & " to sample.txt ") Close #1 intMsg = MsgBox("File sample.txt closed") End Sub * The above program will create a file sample.txt in the My Documents' folder and ready to receive input from users. Any data input by users will be saved in this text file. Reading files To read a file created in the last section , you can use the input # statemment. However, we can only read the file according to the format when it was written. You have to open the file according to its file number and the variable that hold the data. We also need to declare the variable using the DIM command. Sample Program: Reading file Private Sub Reading_Click() Dim variable1 As String Open "c:\My Documents\sample.txt" For Input As #1 Input #1, variable1 Text1.Text = variable1 Close #1 End Sub

Visual Basic and the Data Bases
A database file is a collection of database tables. A table is nothing more than a chart of rows and columns, or a grid...like a spreadsheet. Columns are referred to as fields and always have headings, or field names. An entire row is one record. Each individual table in a database contains related information, but it's not uncommon for a database to consist of just one table. Designing a new database takes careful planning. For optimal performance in multiple table databases, related fields from different tables are linked by having the same field name. VB 5.0 and the Data Control Database files exist in several formats and versions. With VB 5.0, you'll probably be using a Microsoft Jet 3.x database. Microsoft Access 97 is the best "front end" application to use for creating, building, and managing Jet 3.x files. VB 6.0, ADO Data Control, Access 2000, and Jet 4

VB itself comes with a decent front-end database tool called VisData which was written with VB version 5.0. Accessing the information in a database with VB is quite simple and actually can be done without writing code. Placing a Data Control on a form provides a link between your program and the database file. By itself, the Data Control won't display any data, you must have bound controls to do that. To find out if a particular control can be data bound, check to see if it has DataSource property. Here's how its done. Draw a data control on a form. Set the DatabaseName property to an existing .MDB database by bringing up the "DatabaseName" dialog box from the properties window. Now go to the RecordSource property of the Data Control and you'll see a list of all the tables in the database. Only one table can be assigned. You'll need additional Data Controls to display more than one table at a time. Draw a Text Box on the form. First set the DataSource property to the name of the Data Control (Data1 if you're using the default). Now set the DataField property, this time choosing from a list of all the fields in the table. Run the project and the Text Box will contain the data from the first record in that field (making it the current record). To display an entire record, you'll need a bound control for each field, or you might want to try one of the database custom controls (DBGrid, DBList, DBCombo). Be aware that making changes to bound controls changes the actual data in the database. Set a Text Box's Locked property to True to avoid that, or use a Label. Moving around the database

The Data Control has four buttons for moving through its records as you can see above. You can also move through the records with code.
Data1.Recordset.MoveFirst Data1.Recordset.MovePrevious Data1.Recordset.MoveNext Data1.Recordset.MoveLast

The Data control will create a Recordset object to represent the table and allow you to use it as a property. The Recordset object has many useful properties and methods of it's own. These four methods require no arguments and will accomplish the same thing as the user clicking the arrow buttons. A Recordset is just what it implies, a set of records. In the simplest case, the Recordset is the entire table, but you can search databases with a query to work with particular tables, fields, and records. This is done by assigning the RecordSource property of the Data Control to an SQL string instead of a table name. Recordsets can be of three different types:
y y y

Table type (dynamic) Dynaset type (dynamic) Snapshot type (static)

The Table type is one entire table which can be updated (records can be added, deleted, and edited). The Dynaset type allows fields and records from multiple tables and is also updatable. The Snapshot type also allows data from multiple tables, but is not updatable: use this type when you just need to examine data, rather than update it. The RecordsetType property of the Data control can be set to create the desired type. If you do this in code, the following constants are available:
Data1.RecordsetType = vbRSTypeTable Data1.RecordsetType = vbRSTypeDynaset Data1.RecordsetType = vbRSTypeSnapShot

RecordCount property The number of records in your Recordset can be accessed with the RecordCount property of the Recordset object. However, if the Recordset is of Dynaset or Snapshot type, then it will be necessary to populate the Recordset first. Populating a Recordset is accomplished by using the MoveLast method.
Data1.Recordset.MoveLast MsgBox "There are " & Data1.Recordset.RecordCount _ & " records in this Recordset"

It's not necessary to populate a Table type Recordset, nor is it necessary to populate any Recordset unless you need the RecordCount right away. Population of large Recordsets is time consuming. Using the Recordset in other ways will accomplish the population. Field data types

Like variables, properties, and functions, Fields in a database must be of a certain data type. All the data types you're familiar with are available. Microsoft Access uses these data types.
y y y y y y y

Text- String data up to 255 characters Memo- String data up to 1.2 gigabyte Number- Can be further specified as Integer, Long, Single, Double Date/Time- Just like the Date data type Currency- Just like the Currency data type Yes/No- Boolean OLE Object- Used for pictures or other objects.

VB 6.0, ADO Data Control, and Access 2000 The Access 97/Jet 3.x database can still be used with VB 6.0. Access 2000 can convert the file to the new Jet 4 format, but that will not be a good idea if you want to continue using the intrinsic Data control which revolves around DAO. Jet 4 is more comfortable with ADO, the new, easyto-use data object library. If you're starting a new project and database with VB 6.0, you should go all out and use the Microsoft Jet 4 database, Access 2000, and the new ADO Data Control. VisData cannot read the new format. With ADO, the connect string is now your best friend. Here is a connect string from one of my projects:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WINDOWS\ Desktop\ASPProj\board\db\board.mdb;Persist Security Info=False

No one is expecting you to write these connect strings from scratch. With VB 5.0 and the Data control, you would use the DatabaseName dialog box to select the database file. With VB 6.0 and the ADO Data control, you'll set the ConnectionString property with a 4-step connect string "wizard". Once that is done, you'll set the CommandType property to 2 - adCmdTable. This is similar to setting the RecordsetType property of the intrinsic Data control to 0 - Table. Now you can set the Recordsource property in much the same manner as before, but now you'll get a dialog box instead of a drop down list.

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->