Vous êtes sur la page 1sur 26

Object 9 : About GUI and Visual Basic

Visual Basic 6.0 Introduction An integrated development environment (IDE), also known as integrated design environment and integrated debugging environment, is a type of computer software that assists computer programmers to develop software. IDE Contents The Visual Studio IDE consists of several sections, or tools, that the developer uses while programming. As you view the IDE for a new project you generally have three sections in view:

The Toolbox on the left The Solution Explorer on the right The Code / Design view in the middle

Toolbox The Toolbox is a palette of developer objects, or controls, that are placed on forms or web pages, and then code is added to allow the user to interact with them. An example would be TextBox, Button and ListBox controls. With these three controls added to a Windows Form object the developer could write code that would take text, input by the application user, and added to the ListBox after the button was clicked. Solution Explorer This is a section that is used to view and modify the contents of the project. A Visual Studio Windows Application Project will generally have a Form object with a code page, references to System components and possibly other modules with special code that is used by the application. Properties Windows The properties windows shows all the control (like textbox) properties to be change at design time. Most of these properties can be change at run time with some code, but basically most of this properties change the way the control is display on your application. Code / Design view This is where the magic takes place. Forms are designed graphically. In other words, the developer has a form on the screen that can be sized and modified to look the way it will be displayed to the application users. Controls are added to the form from the Toolbox, the color and caption can be changed along with many other items. This center window of the IDE is also where developers write the code that makes everything in the application work. The code is written in modules, or files, that are either connected to an object (Forms) or called specifically when needed.

A brief description of Visual Basic 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 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.

Introduction to Forms Forms are the first Microsoft Visual Basic objects you get acquainted with. Although you can write useful programs with only rudimentary user interfacescommand-line driven utilities, for examplemost Visual Basic applications include one or more forms, and so you need to be familiar with their properties and features. Intrinsic Controls TextBox Controls TextBox controls offer a natural way for users to enter a value in your program. For this reason, they tend to be the most frequently used controls in the majority of Windows applications. TextBox controls, which have a great many properties and events, are also among the most complex intrinsic controls. In this section, I guide you through the most useful properties of TextBox controls and show how to solve some of the problems that you're likely to encounter.

Label Controls Most people use Label controls to provide a descriptive caption and possibly an associated hot key for other controls, such as TextBox, ListBox, and ComboBox, that don't expose the Caption

property. In most cases, you just place a Label control where you need it, set its Caption property to a suitable string (embedding an ampersand character in front of the hot key you want to assign), and you're done. Caption is the default property for Label controls. CommandButton Controls Using CommandButton controls is trivial. In most cases, you just draw the control on the form's surface, set its Caption property to a suitable string (adding an & character to associate a hot key with the control if you so choose), and you're finished, at least with user-interface issues. To make the button functional, you write code in its Click event procedure, as in this fragment: Private Sub Command1_Click() ' Save data, then unload the current form. Call SaveDataToDisk Unload Me End Sub CheckBox Controls CheckBox controls are useful when you want to offer your users a yes or no, true or false choice. Anytime you click on this control, it toggles between the yes state and the no state. OptionButton Controls OptionButton controls are also known as radio buttons because of their shape. You always use OptionButton controls in a group of two or more because their purpose is to offer a number of mutually exclusive choices. Anytime you click on a button in the group, it switches to a selected state and all the other controls in the group become unselected ListBox Controls ComboBox Controls

Object 10 -Design a program to display regional languages of different states in India. Take many names of status of India in one list box control and other text box control should display their languages e. g. Maharashtra Marathi etc.

Code Private Sub Form_Load() List1.text= Text1.text= Label1.caption=Select Language Label2.caption=State List1.AddItem ("Hindi") List1.AddItem ("Marathi") List1.AddItem ("Telgu") List1.AddItem ("Orria") List1.AddItem ("Kannnada") List1.AddItem ("Malyalam") List1.AddItem ("Gujrati") End Sub

Private Sub List1_Click() Dim i As Integer If List1.ListIndex = -1 Then

Exit Sub For i = List1.ListCount - 1 To 0 step -1 If List1.Selected(i) = True Then If List1.List(i) = "Hindi" Then Text1.Text = "MP, Delhi" ElseIf List1.List(i) = "Marathi" Then Text1.Text = "Maharastra" ElseIf List1.List(i) = "Telgu" Then Text1.Text = "Andra Pradesh" ElseIf List1.List(i) = "Orria" Then Text1.Text = "Orrisa" ElseIf List1.List(i) = "Kannnada" Then Text1.Text = "Karanataka" ElseIf List1.List(i) = "Malyalam" Then Text1.Text = "Kerla" ElseIf List1.List(i) = "Gujrati" Then Text1.Text = "Gujrat" End If End If Next i End Sub

Data Types in Visual Basic 6.0 There are many types of data we come across in our daily life. For example, we need to handle data such as names, adresses, money, date, stock quotes, statistics and etc everyday. Similarly In Visual Basic, we are also going to deal with these kinds of data. However, to be more systematic, VB divides data into different types. Numeric Data Types Numeric data are data that consists of numbers, which can be computed mathematically with various standard operators such as add, minus, multiply, divide and so on. In Visual Basic, the numeric data are divided into 7 types. Type Storage Range of Values 1)Byte 1 byte 0 to 255 2)Integer 2 bytes -32,768 to 32,767 3)Long 4 bytes -2,147,483,648 to 2,147,483,648 4)Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values 1.401298E-45 to 3.402823E+38 for positive values. 5)Double 8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for negative 4.94065645841247E-324 to 1.79769313486232e+308 for positive values. 6)Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807 7)Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use

+/- 7.9228162514264337593543950335 (28 decimal places).

Nonnumeric Data Types Data Type Storage Range 1)String(fixed length) Length of string 1 to 65,400 characters 2)String(variable length) Length + 10 bytes 0 to 2 billion characters 3)Date 8 bytes January 1, 100 to December 31, 9999 4)Boolean 2 bytes True or False 5)Object 4 bytes Any embedded object 6)Variant(numeric) 16 bytes Any value as large as Double 7)Variant(text) Length+22 bytes Same as variable-length string

Suffixes for Literals Literals are values that you assign to a data. In some cases, we need to add a suffix behind a literal so that VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double type data. Suffix Data Type & Long ! Single # Double @ Currency In additon, we need to enclose string literals within two quotations and date and time literals within two # sign. Strings can contain any characters, including numbers. The following are few examples: memberName="Turban, John." TelNumber="1800-900-888-777" LastDay=#31-Dec-00# ExpTime=#12:00 am# The following are the rules when naming the variables in Visual Basic It must be less than 255 characters No spacing is allowed It must not begin with a number

Declaring Variables In Visual Basic, one needs to declare the variables before using them by assigning names and data types. They are normally declared in the general section of the codes' windows using the Dim statement. The format is as follows: Dim variableNmae as DataType

Dim password As String Dim yourName As String Dim firstnum As Integer Dim secondnum As Integer Dim total As Integer Dim doDate As Date You may also combine them in one line , separating each variable with a comma, as follows: Dim password As String, yourName As String, firstnum As Integer,............. If data type is not specified, VB will automatically declares the variable as a Variant.

Create and save a new program 1. Start VB. Find Visual Basic on the Windows Start menu and start it. The large VB window appears with a New Project dialog box (if there is no dialog box, bring it up by File > New Project). Select Standard Exe. The VB window shows Project1 with an empty Form1. 2. Name the project. Select Project > Project1 Properties. In the Project Properties dialog box, change Project1 to your project name, say Counter. The title bar on the VB window changes to match. 3. Name the form and set the form caption. The Properties window at the right of the VB window shows the properties for the form. The first property at the top of the list is Name. Change the name to, say, frmCounter. The title bar in the Form window changes to match. Still in the Properties window, scroll down to Caption. Change the caption to the same name as the project, say Counter. The title bar on the form itself changes to match. 4. Save the form (you should always name and save the form before you save the project). Select File > Save frmCounter As .... The Save Form As dialog box appears. The Save in: textbox shows the name of the folder where the form will be saved. You should create a new folder for this project. Navigate to the folder where you want to keep all your VB projects and click on the new folder icon (a picture of a folder with a little highlight). After you create the new folder, select that folder. Its name should appear in the Save

in: box. The form file name frmCounter.frm should appear in the File name: box (if not, type in the correct name). Click on Save. The form is saved. 5. Save the project (be sure to name and save the form before you save the project). Select File > Save Project As .... The Save Project As dialog box appears. The Save in: textbox should show the correct folder (the one you just created for the form). The File name: box should show the correct name (Counter.vbp in this example). Click on Save. The project is saved. After you name and save the form and the project, it is a good idea to exit and then restart VB to make sure you can restore your project --- before you invest a lot of work in it. Restore a saved program 1. Start VB. Find Visual Basic on the Windows Start menu and start it. The large VB window appears with a New Project dialog box. This time choose the Existing tab (if there is no dialog box, bring it up by File > Open Project). Navigate to the folder you created earlier. It should contain a .vbp file for the project you created earlier (Counter.vbp in this example). Select that file. Alternatively, instead of using the Start menu, you can navigate to the project folder using My Computer or Windows Explorer. Then double-clicking on the .vbp file or the .frm file starts VB and opens that project. The restored project appears in the VB window. The project name appears in the title bar. 2. Open the form. An icon for a folder of forms appears in the Project window on the right side of the VB window. Open this folder and select the form you saved. Click on the View Code and View Object icons to display the code or form layout windows. Now you are ready to add controls and code to the form. At any time, you can use File > Save frmCounter and File > Save Project to save your changes to the form and the project without going through the Save As ... dialogs. Write a program based on an earlier program 1. Restore a saved VB program, as described in How to Restore ... above. 2. It is a good idea to change the project name and the form name, as described in How to Create ... above.

3. Make changes in the program. 4. Save the form and the project in a new folder, using Save As ... (not Save) as described in How to Create ... above. Make sure you save the changed program in a different folder. This is necessary to ensure that the earlier program is preserved. Be sure to save the form first. Add controls(tools) to the form Repeat for each control: 1. Choose the control. In the Toolbox window at the left, point at a control icon. The name of the control (for example, Label) will appear. Double click on the control icon. The control appears in the middle of the form layout window. 2. Position and size the control. In the Form Layout window, point at the center of the control. Drag control to the position you want (hold down the left mouse button while you move the mouse). To size the control, point at one of the little grab boxes at the sides and corners of the control. Drag the side (or corner) to make the size you want. It is best to set the properties for each control right after you select it and position it. Set control properties For each control: 1. Use the Properties window at the right. Select the control from the drop-down menu at the top of the Properties window. Or, click on the control in the form layout window. A table showing all the control properties appears, with property names in the left column and property values in the right. 2. The first property is Name. Type in a meaningful name, using the naming conventions: frm... for forms, cmd... for command buttons, lbl... for labels, tmr... for timers etc. 3. Set the other properties. For command buttons, set alignment, caption and font. For labels, set alignment, caption, font, and (often) background color. For timers, set interval. And so on. Write code for event subroutines

For each pertinent control and event: Use the Code window. Find the relevant event subroutine. For controller Ctlr and event Event, the subroutine is named Ctlr_Event, for example cmdEnter_Click. Double-clicking on the controller in the Form layout window puts the cursor at the pertinent subroutine in the Code window. Run the program There are several ways to run your program:

Press the F5 key. On the VB menu bar, Run > Start On the VB toolbar, click the VB Run icon (the arrow)

The program window appears, looking much like the form you designed. The controls on the window are active. While the program is running, it behaves like any other window on the desktop: you can move it, minimize it, etc. The indicator on the VB window title bar changes from design mode to run mode. Many items in the VB window disappear during run mode and many menu and toolbar operations not enabled. Stop the program There are several ways to stop your program:

In your program's window, click the Exit button or menu (if you provided one) In your program window's title bar, click the Close button (VB always provides one) On the VB menu bar, Run > Stop On the VB toolbar, click the VB Stop icon (the box)

The indicator on the VB window title bar changes from run mode to design mode. Items in the VB window reappear, and menu and toolbar operations are enabled again. Revise the program In design mode, you can add or remove controls, change control properties and revise code. Your changes will be in effect when you run the program again. It is not necessary to use the Save operations before your next program run. It is only necessary to save before you exit VB. Exit There are several ways to exit VB.

On the menu bar, File > Exit On the VB window title bar, click the Close button

Object 11 Add two numbers.


Step1 : Create three text boxes ,Three Labels and one command button.

Step2: Open code window and write the following code. Private Sub Form_Load() Form1.Caption = "Addition" Text1.Text = "" Text2.Text = "" Label1.Caption = "Enter the First Number" Label2.Caption = "Enter the Secomnd Number" Text3.Text = "" Label3.Caption = "Result is:" Command1.Caption = "Sum" End Sub

Step 3) Write code for addition of two numbers in code window. Private Sub Command1_Click() Text3.Text = Val(Text1.Text) + Val(Text2.Text) End Sub Step 4) Run the pogram and as soon as we click on Sum button ,it will give summation of text1 and text 2 and gives result in text3 text box. Note: Val converts text into numeric values. If we do not use val than it will concatenate values of both text boxes.

Object 12) Print the following :

0 1 2 3 4 5 6 7 8 9 10 Private Sub Form_Load() Form1.Caption = "Addition" Form1.Show For i = 0 To 10 Print ( i) Next i End Sub

Object 13 ) Make a simple Calculator for addition, subtraction ,multiplication and division
Step1) Add three labels, three text boxes and four command buttons to the form

Step2) Write the following code in code window Private Sub Form_Load() Form1.Caption = "Calculator" Text1.Text = "" Text2.Text = "" Text3.Text = "" Label1.Caption = "Enter the first Number" Label2.Caption = "Enter the Second Number" Label3.Caption = "Result is" Command1.Caption = "+" Command2.Caption = "-" Command3.Caption = "*" Command4.Caption = "/" End Sub Step3) Add following code to command buttons events click() Private Sub Command1_Click() Label3.Caption = "Sum is" Text3.Text = Val(Text1.Text) + Val(Text2.Text) End Sub Private Sub Command2_Click() Label3.Caption = "Subtraction is " Text3.Text = Text1.Text - Text2.Text End Sub

Private Sub Command3_Click() Label3.Caption = "Multiplication is" Text3.Text = Text1.Text * Text2.Text End Sub Private Sub Command4_Click() Label3.Caption = "Division is" Text3.Text = Text1.Text / Text2.Text End Sub

Step5) Execute the program we will get this out put.

Step6) on pressing any command button we will get following output

Object14) Demonstrate Drive list box, Directory list box and file list box

Step1) Add one drivelist box, directorylist box and one file list box to form.

Step2) Need to establish connection among these objects. So need to write the following code in code window. Default event of all the objects are change(). As soon as we change our option from any object,effect will be produced ot corresponding object.

Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub Form_Load() Form1.Caption = "Demo" End Sub Step3) Run the program we will get this type of output.

Object 15 )Database Connectivity

Visual basic provides database connectivity facility apart from the facility of user friendly interface. We can establish connection to any type of database like Oracle,MS Assess, MYSQL, excel sheet etc. This can be done in many ways(Data Environment etc) but following two are most widely used. 1) DAO (Data access Object) 2) ADO (ActiveX data Object) Object 6) Using DAO: Adding Data object in toolbox. Step1) Add Data Object to form. Step2) Add Data bound grid control(To show data in table format) to toolbox using Project->Components->MicroSoftDatabound grid control sp3 Step3) Draw DBGRID to form.

Step4) Go to property of Data object and change the following properties Database : Access DatabaseName: C:\Program Files\Microsoft Visual Studio\VB98\BIBLIO.MDB Recordsettype: 0-Table Recordsource: Authors Step5) Go to property of DBGRID and change the following property Datasource: DATA1 Step6) Execute the program. We get the content of Author table in GRID.

Note : We can run queries to perform specific tasks using different events. Object7) Using ADO. Step1) App Microsoft ADO data object and Datagrid control6.0(To view the content of table) . Project->components->Microsoft ADO data control 6.0 Project->components->Microsoft DtaGrid Control6.0

Step2) Draw both controls on form as follows.

Step3) Go to Control panel->administrative services->Datasource (ODBC)

Note :ODBC acts as an interface between program and Database. Click on Add button we get list of drivers. Choose any one as per need (Microsoft access Driver(*. mdb)) and click finsh.

We get following window

Choose appropriate data base by pressing select button and give any convenient name in Data source name For our convenience we have selected the data base : C:\Program Files\Microsoft Visual Studio\VB98\BIBLIO.MDB And have given Data source name as Demo. We get the following window

Now ODBC has been established.

Step4) again go to property window of ADODC and click connection string we get following window

Select the second option and choose the demo from combo box. Step4) Click on record source property we get following window

Choose command type as table format and choose table of database and press OK. Step5) go to property of DATAGRIG and change the following properties Datasource: ADODC1 Step6) Write the following code to change the caption of form. Private Sub Form_Load() Form1.Caption = "Database ADODC"

End Sub

Step7)Execute the program .We get following output.

Note : We can run queries to perform specific tasks using different events. We can use different database software also like Oracle,MYSQL etc.

Vous aimerez peut-être aussi