Вы находитесь на странице: 1из 33

SET I

1. Write about the Visual Basic Application Development Life cycle with a sample forms development for performing integer arithmetic operations. A. The important steps, referred to as Development cycle by Programmers, in creating a Visual Basic Program are: y Decide what you want the computer to do. y Decide how you want your program to look on the screen. (The appearance of your program is called user interface). y Draw your user interface by using common components, such as windows, menus and command buttons. (The components of user interface are called objects or controls). y Define the name, color, size and appearance of each user interface object. (An objects characteristics are called properties). y Write instructions in BASIC to make each part of your program to do something. (BASIC instructions are called command). y Run your program to see whether it works. y Fix any error (or bugs) in your program. Develop an Attractive User Interface

The user interface is what someone sees when your program is running. Every program has a user interface in one form or another. Some programs have elaborate, colorful windows while other programs have a simple appearance.

A VisualBasic user interface consists of forms and objects. A form is nothing more than a window that appears on the screen. Most VisualBasic programs have at least one form, although most programs use several forms.

Objects our items that appear on a form, such as a command button, scroll bar, option button or check box. An object enables the user to give commands to your program.

Define Properties

After you create a form and draw some objects on the form, the next step is to define the properties of each form and object. An objects properties determine the objects name, color, size, location and appearance on the screen.

Different objects have different properties. Each time you draw an object on a form, VisualBasic assigns default property values, which define a generic object that nobody, can really use. If you want to customize an object, you need to define one or more properties for each object used by your program. Write The Code

The final step involves writing the BASIC commands (also known as code) to make your program actually work. If you want to edit the appearance of your user interface, you can go back and alter it at any time.

The whole purpose of VISUALBASIC code is to tell the object on a form what to do when the user does something. For example, if the user clicks on an OK or CANCEL command button, nothing happens unless you have written BASIC commands to tell your computer exactly what to do.

Any time a user presses a key , moves the mouse, or clicks the mouse button, such an action is called an event. Whenever an even occurs, the code written for that even gets executed (sometime referred to as fired)

Essentially, writing VISUALBASIC program means drawing your user interface and then writing BASIC code or procedures to make the user interface work.

2:

Discuss the following: y y y Form Modules Standard Modules Class Modules B. (i) Form Modules : Form modules (.FRM file name extension) are the foundation of most Visual Basic applications. They can contain procedures that handle events, general procedures, and form-level declarations of variables, constants, types, and external procedures. If you were to look at a form module in a text editor, you would also see descriptions of the form and its controls, including their property settings. The code that you write in a form module is specific to the particular application to which the form belongs; it might also reference other forms or objects within that application. Virtually everything that applies to class module applies to form module. Forms are just class modules that can have controls placed on them and display a form window. Forms are part of our application that are visible to users at runtime.

(ii) Standard Modules:

Standard Modules ( .BAS extension) are containers for procedures and declarations, commonly used by other parties of our application. They can contain global or module level declarations of types, constant, variables, external procedures and global procedures.

(iii) Class Modules:

Class Modules ( .CLS extension) are foundation of object oriented programming in VB. We can write code in class modules to create new objects. The new objects can include our own customized properties and methods, although custom objects can not have their own events. Other objects, in our application, can also use all the properties

and methods we create. We can also use the keyword, NEW to create multi copies of our objects.

2. Create a Menu Interface in Visual Basic which performs the same functionality of MS Word File Menu.

A. Input Form

Codings:

Private Sub mnufileexit_Click() End

End Sub

Private Sub mnufilenew_Click() Dim reply reply = MsgBox("Save the current file?", vbYesNo, "SAVE...") If reply = vbYes Then mnufilesave_Click End If frmmain.txtedit.Text = "" sfile = ""

End Sub

Private Sub mnufileopen_Click() CommonDialog1.ShowOpen sfile = CommonDialog1.FileName Open sfile For Input As #2 frmmain.txteditbox.Text = Input(LOF(2), 2) Close #2

End Sub

Private Sub mnufilesave_Click() If sfile = "" Then CommonDialog1.Filter = "text files|*.TXT|batch files|*.BAT|INI files|*.ini"

CommonDialog1.FilterIndex = 1 CommonDialog1.Action = 2 sfile = CommonDialog1.FileName End If Open sfile For Output As #2 Print #2, frmmain.txteditbox.Text Close #2

End Sub

Private Sub mnufilesaveas_Click() sfile = "" mnufilesave_Click

End Sub

Output Forms

4. Develop a University Database using MS Access. Create appropriate form based interfaces to access the data using controls in the tool box.

Set II

1 . Discuss the following:

y y y

Visual Basic Editions Object Naming Conventions Event Procedures

A. Visual Basic Editions: Visual Basic is available in three editions, each geared to meet a specific set of development requirements. The features available to you depend on which product you have purchased.

Visual Basic Enterprise Edition Features

The Visual Basic Enterprise Edition contains all of the features included with the Visual Basic Professional Edition and the Visual Basic Learning Edition. In addition, it contains the following features, available in the Enterprise Edition only. RemoteData Control The Remote Data control implements data access by using RDO, the Microsoft Remote Data Objects. SQL Debugging The T-SQL debugger allows you to interactively debug remote stored procedures written in Microsoft SQL Server's Transact SQL dialect, from within the Visual Basic development environment. The Microsoft SQL Server Programmer's Toolkit covers Transact-SQL, programming ODBC for SQL, and much more. Stored Procedure Editor The SQL Editor allows you to create and edit stored procedures and triggers in both SQL Server and Oracle from within the Visual Basic development environment. UserConnection Designer This ActiveX designer provides design-time support for programmatic data access. This tool has been superseded in this version of Visual Basic by the Data Environment designer, listed above.

This tool stores, organizes, and shares reusable components. It can contain wizards, ActiveX components, Database Connection objects, and many other components used in Visual Basic projects. It is suited to enterprise-wide component cataloguing and reuse because it is based on the open and scalable Microsoft Repository. Visual Database Tools Integration (Query Designer and Database Designer) With these designers you can visually create and modify database schemas and queries: Create SQL Server and Oracle database tables, drag and drop to create views, and automatically change column data types. This source-control tool tracks changes to files and stores the changes so that files, for example code modules, can be easily and economically reused. y Visual Basic Learning Edition

The Visual Basic Learning edition allows programmers to easily create powerful applications for Microsoft Windows and Windows NT. It includes all intrinsic controls, plus grid, tab, and databound controls. Documentation provided with this edition includes Learn VB Now (a multimedia CD-ROM title), plus Microsoft Developer Network CDs containing full online documentation.

- Object Naming Conventions

Objects should be named with a consistent prefix that makes it easy to identify the type of object. Recommended conventions for some of the objects supported by Visual Basic are listed below. Suggested Prefixes for Controls Control type 3D Panel ADO Data Animated button Check box Combo box, drop-down list box prefix pnl ado ani chk cbo Example pnlGroup adoBiblio aniMailBox chkReadOnly cboEnglish

Command button Common dialog Communications Control (used within procedures when the specific type is unknown) Data Data-bound combo box Data-bound grid Data-bound list box Data combo Data grid Lightweight text box Lightweight vertical scroll bar Line List box ListView MAPI message MAPI session MCI

cmd dlg com ctr

cmdExit dlgFileOpen comFax ctrCurrent

dat dbcbo dbgrd dblst dbc dgd lwtxt lwvsb lin lst lvw mpm mps mci

datBiblio dbcboLanguage dbgrdQueryResult dblstJobType dbcAuthor dgdTitles lwoptStreet lwvsbYear linVertical lstPolicyCodes lvwHeadings mpmSentMessage mpsSession mciVideo

Menu Month view MS Chart MS Flex grid MS Tab OLE container Option button Picture box Picture clip ProgressBar Remote Data RichTextBox Shape Slider Spin StatusBar SysInfo TabStrip

mnu mvw ch msg mst ole opt pic clp prg rd rtf shp sld spn sta sys tab

mnuFileOpen mvwPeriod chSalesbyRegion msgClients mstFirst oleWorksheet optGender picVGA clpToolbar prgLoadFile rdTitles rtfReport shpCircle sldScale spnPages staDateTime sysMonitor tabOptions

Text box Timer Toolbar TreeView UpDown Vertical scroll bar

txt tmr tlb tre upd vsb

txtLastName tmrAlarm tlbActions treOrganization updDirection vsbRate

- Event Procedures

An Event procedure is predefines by VBA in the sense that you cannot change the name of the procedure, nor the object within Excel to which the procedure belongs, nor the conditions under which the procedure is triggered. Program code are executed when they are triggered by an event (like the Worksheet_Activate event) You can create event procedures for these events in a generic class module. Though the class module isn't associated with the object by default, it can contain event procedures for an object that has events. If you consider event procedures in a form module, you may realize that those event procedures exist only for a particular instance of the form. For example, UserForm1 and UserForm2 are separate instances of an object of type UserForm. Both have an Initialize event, which occurs only when that form is loaded. The Initialize event procedure for UserForm1 runs only when UserForm1 is loaded, not when UserForm2 is loaded, and vice versa. The same holds true for events on objects that don't have associated modules an event occurs for a particular instance of an object. More specifically, it occurs for an instance of an object that you've indicated should respond to events, not for any other instance. To indicate that an instance of an object should respond to events, you declare a module-level object variable of that type by using the WithEvents keyword in a class module. This keyword notifies VBA that you want to respond to events for the instance that is assigned to that object variable. You can use the WithEventskeyword only with objects that support events, and only in a class module.

For example, the following line of code in a class module declares a private object variable of type Excel.Application to respond to events: Private WithEvents xlApp As Excel.Application Once you've declared an object variable to respond to events, that object variable appears in the Object box in the class module's Code window, and its events appear in the Procedures box in the Code window. To create an event procedure stub, click the object name and event name in these boxes. The Visual Basic Editor inserts an event procedure stub for you that looks like the following: Private Sub xlApp_NewWorkbook(ByVal Wb As Excel.Workbook) End Sub At this point, you've created an object variable that has associated events, and an event procedure. The object variable doesn't yet point to anything, however. You need to assign a reference to it, which you can do in the Initialize event procedure for the class module. The Initialize event occurs as soon as a new instance of the class is created, so if you assign a reference to the object variable here, you can always be sure it will exist when you need it. In this case, you want the object variable to point to the current instance of the application: Private Sub Class_Initialize() Set xlApp = Application End Sub Finally, you need to create a new instance of the class in order to trigger the Initialize event and load the event-ready Application object variable into memory. Insert a new standard module, and declare a private module-level object variable that will point to the instance of the class. For example, if the class is named XLEvents, you can declare the following object variable: Private p_evtEvents As XLEvents You must declare this object variable at the module level, so that it will remain in memory until the project is closed or reset, since this object variable points to the class that contains the eventready object and its event procedures. Otherwise, the object will no longer respond to events once the variable has gone out of scope. Next, add the procedure that creates the new instance of the class in a standard module: Public Sub InitXLEvents() Set p_evtEvents = New XLEvents End Sub After you run this procedure, any code you've added to the Application object's event procedures will run when the corresponding Application object event occurs.

2. Discuss the following control structures of Visual Basic with suitable programming examples for each: y y y y If Statements Case Statements Do While Loop ForNext Loop

If Statements

Conditional Logic - If Statements What is conditional logic? Well, it's something you use in your daily life all the time, without realising you're doing it. Suppose that there is a really delicious cream cake in front of you, just begging to be eaten. But you are on a diet. The cake is clearly asking for it. So what do you do, eat the cake and ruin your diet? Or stick to your diet and let somebody else have that delicious treat? You might even be saying this to yourself: If I eat the cake Then my diet will be ruined If I don't eat the cake Then I will be on course for a slimmer figure Note the words If and Then in the above sentences. You're using conditional logic with those two words: "I will eat the cake on condition that my diet is ruined". Conditional logic is all about that little If word. You can even add Else to it. If I eat the cake Then my diet will be ruined Else If I don't eat the cake Then I will be on course for a slimmer figure And that is what conditional Logic is all about - saying what happens if one condition is met, and what happens if the condition is not met. Visual Basic uses those same words - If, Then, Else for conditional Logic. Let's try it out. Start a new project. Give it any name you like. In the design environment, add a Button to the new form. Double click the button and add the following code to it: Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click

Dim firstname As String firstname = "Bill" If firstname = "Bill" Then MsgBox("firstname is Bill") End Sub Note that we start a new line after the word Then. 1. The first line contains our condition: "If the following condition is met". 2. The second line is what we want to do if the condition is indeed met. 3. The third line tells Visual Basic that the If statement ends right here.

Case Statements

The Select Case statement is another way to test what is inside of a variable. You can use it when you know there is only a limited number of things that could be in the variable. For example, suppose we add another choice for that cream cake. We've only said that the consequences of eating the cream cake is that the Diet will be either "Ruined" or "Not Ruined". But what if we add another option - "Diet Not Tested". In other words, we ate the cake but refused to climb onto the scales to weigh ourselves! Remember: all we are doing is testing what is inside a variable, in this case a variable called creamcake. Once we decide what is inside the variable, we can take some action. So let's look at how the Select Case works.

Select Case creamcake Case "Eaten" DietState = "Diet Ruined" Case "Not Eaten" DietState = "Diet Not Ruined" Case Else DietState = "Didn't check" End Select

Do While Loop

With a Do Loop we can use word s like "While" and "Until". And then we can say, "Go round and round the loop While there's still text to be read from the file." An example might make things clearer. Load the form you created for the last exercise, the one that has two textboxes and a Button and tested your understanding of For loops. Add another button to the Form. Your form might look something like this:

Double click the new button to open the code window, and then type the following code for the new button: Dim number as Integer number = 1 Do While number < 5 MsgBox number number = number + 1 Loop When you've finished, run the programme and see what happens. The numbers 1 to 4 should have displayed in your message box. So the Do loop keeps going round and around. And when it gets to the top, it tests the "While" part - Do While number is Less Than 5. It's really answering a Yes or No question: is the number inside the variable called number Less Than 5? If it is Less Than 5, go round the loop again. If it's not Less than 5, Visual Basic jumps out of the Loop entirely.

You can add the "While ... " part to the bottom, just after the word "Loop". Like this: Do number = number + 1 Loop While number < 5

For.Next Loop

This first type of loop we'll look at is called a For Loop. It is the most common type of loop you'll use when you programme. We'll use one to add up our 4 numbers, and then discuss the code. Study the following. In fact, create a new Project. Add a button to your new Form. Double click your new button and type the following code for it: Dim answer As Integer Dim startNumber As Integer answer = 0 For startNumber = 1 To 4 answer = answer + startNumber Next startNumber We start by setting up two integer variables. We set one of these to zero. Then we start our loop code. Let's examine that in more detail. For startNumber = 1 To 4 answer = answer + startNumber Next startNumber We start our loop by telling Visual Basic what type of loop we want to use. In this case it is a For loop: For startNumber = 1 To 4 The next thing you have to do is tell Visual Basic what number you want the loop to start at:

For startNumber = 1 To 4 Here we are saying "Start the loop at the number 1". The variable startNumber can be called anything you like. A popular name to call a start loop variable is the letter i ( i = 1). So what we're doing is setting up a variable - the start of the loop variable - and putting 1 into it; Next, you have to Tell Visual Basic what number to end the loop on: For startNumber = 1 To 4 The To word, followed by a number or variable, tells Visual Basic how many times you want the loop to go round and round. We're telling Visual Basic to loop until the startNumber variable equals 4 The command that tells Visual basic to grab the next number in the sequence is this: Next startNumber When Visual Basic reaches this line, it checks to see what is in the variable startNumber. It then adds one to it. In other words, "Get me the next number after the one I've just used." The next thing that happens is that Visual Basic will return to the word For. It returns because its in a loop. It needs to know if it can stop looping. To check to see if it can stop looping, it skips the startNumber = 1 part, and then jumps to your end number. In our case, the end number was 4. Because Next startNumber adds one to whatever is in startNumber, then startNumber is now 2 (It was 1 at the start. The next number after one is ... ?). So if startNumber is now 2, can Visual Basic stop looping? No it cant. Because weve told it to loop until it reaches number 4. Its only reached number 2, so off it goes on another trip around the loop. When the startNumber is greater than the end number, Visual Basic drops out of the loop and continues on its way. But remember why we're looping: so that we can execute some code over and over again. To clarify things, change the above code to this: Dim startNumber As Integer For startNumber = 1 To 4 MsgBox("Start Number = " & startNumber) Next startNumber Run the programme, and click your button. What happens? You should have seen this in the message box, one after the other:

Start Number = 1 Start Number = 2 Start Number = 3 Start Number =4 Each time round the loop, the code for the message box was executed. You had to click OK four times - startNumber = 1 To 4.

3. Create an MDI Application of your own in Visual Basic with atleast 3 child forms under the Parent Form

A.

Form1

Form2

Form3

MDI Form

Codings:

MDI Form Private Sub MDIForm_Load() Form1.Show End Sub

Private Sub Mnufileexit_Click() End End Sub

Private Sub Mnufilenew_Click()

Form2.Hide Form3.Hide

Form1.txtcustname.Text = "" Form1.txtaccno.Text = "" Form2.txtprinamt.Text = "" Form2.txtintrate.Text = "" Form2.txttime.Text = "" Form3.txtname.Text = "" Form3.txtstbal.Text = "" Form3.txtintamt.Text = "" Form3.txtaccno.Text = "" Form3.txttime.Text = "" Form3.txtbal.Text = "" Form3.txtintrate.Text = "" Form1.Show

End Sub

Form1 Option Explicit Private Sub cmdcontinue_Click() Form3.txtname.Text = UCase(txtcustname.Text) Form3.txtaccno.Text = UCase(txtaccno.Text) Form2.Show

End Sub

Form2 Private Sub cmdback_Click() Form2.Hide Form3.Hide Form1.Show

End Sub

Private Sub cmdcontinue_Click() Dim princ As Currency, interest As Single, years As Single Dim interestearned As Currency, accountbalance As Currency prin = Val(txtprinamt.Text) interest = Val(txtintrate.Text) years = Val(txttime.Text) interestearned = (prin * interest * years) / 100 accountbalance = princ + interestearned Form3.txtstbal.Text = Format(princ, "currency") Form3.txtintrate.Text = Format(interest / 100, "percent") Form3.txttime.Text = years Form3.txtintamt.Text = Format(interestearned, "currency") Form3.txtbal.Text = Format(accountbalance, "currency") Form3.Show

End Sub

Form3 Private Sub cmdback_Click() Form2.Show

End Sub

OUTPUT FORMS

4. Discuss with the help of a programming example all the features of Data Access Objects (DAOs) in Visual Basic A. In Visual Basic 6.0, data access is accomplished using ActiveX Data Objects (ADO). In Visual Basic 2008, data access is accomplished using ADO.NET, which is a part of the .NET Framework. There are a number of differences, both conceptually and in terms of tasks, between the two technologies. For more information on conceptual differences between ADO and ADO.NET, see Comparison of ADO.NET and ADO. In Visual Basic 6.0, there are two common methods of implementing data access in an application: at design time, by binding to an ADODC (ADO data control) or by using a Data Environment, or at run time by creating and interacting with Recordset objects programmatically. In Visual Basic 2008, there are two analogous methods of implementing data access: at design time by using data adapters and datasets, or at run time by adding code to create data adapters and datasets programmatically. For more information, see Creating Data Adapters. In Visual Basic 6.0, data binding is accomplished by setting the binding-related properties of a control: DataChanged, DataField, DataFormat, DataMember, and DataSource. In most cases, the display property of a control (for example, the Text property of a TextBox control) is bound to a field in a data source. In Visual Basic 2008, data binding has a much broader definitionyou can bind any property of any control to any structure that contains data. Binding in Windows Forms is accomplished by means of a DataBindings property that contains a collection of Binding objects for the control. For more information, see Data Binding and Windows Forms. Database Object The first thing you must do in your application is to open a database where your tables are stored. You need to declare a variable to hold your database in order to do this. This is done with: Dim dbMyDB As Database This gives you a variable/object that can hold a reference to your database. To open a simple Access database named "MyDatabase.mdb", do this: Set dbMyDB = OpenDatabase("MyDatabase.mdb") You should really specify the complete path to the db, but if your current directory is the directory where the database is situated, this will work. So, now you have opened a database. This won't give you any data. What you need to do is open a table in the database. You're not limited to open a single table; sometimes you have two or more tables that are related to each other and linked together w ith foreign keys, and there are ways to handle this to. But in this "Visual Basic - Database Primer" I will only show you how to open a single table.

RecordSet Object Visual Basic uses an object called RecordSet to hold your table. To declare such an object and to open the table, do this: Dim rsMyRS As RecordSet Set rsMyRS = dbMyDB.OpenRecordSet("MyTable", dbOpenDynaset) What happened there? Well, I declared a RecordSet object and used the Database object's OpenRecordSet method to open a table of type Dynaset. You can open a RecordSet in several modes. VB's online help file explains the different modes and what they ar e for. The Dynaset mode is the mode I use mostly. It gives you a RecordSet that you can add, delete and modify records in. Accessing records Now that we have opened a table (referred to as RecordSet from now on) we want to access the records in it. The RecordSet object allows us to move in it by using the methods MoveFirst, MoveNext, MovePrevious, MoveLast (among others). I will use some of these to fill up a list box with the records of our RecordSet. To get this example to work, make a database (with Access) called "MyDatabase.mdb" with the table "MyTable" in it. This table should have the fields "ID" of type "Counter" that you set to be the primary key, the field "Name" of type Text and a field "P hone" of type Text. Add some records to it. Put a list box on a form and call it "lstRecords". Dim dbMyDB As Database Dim rsMyRS As RecordSet Private Sub Form_Load() Set dbMyDB = OpenDatabase("MyDatabase.mdb") Set rsMyRS = dbMyDB.OpenRecordSet("MyTable", dbOpenDynaset) If Not rsMyRS.EOF Then rsMyRS.MoveFirst Do While Not rsMyRS.EOF lstRecords.AddItem rsMyRS!Name lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID rsMyRS.MoveNext Loop End Sub This will make the list box fill up with your records when the form loads. I have introduced some new concepts with this example. We have all ready covered the first part where we open the table. The line that says If Not rsMyRS.EOF Then rsMyRS.MoveFirst tells the program to move to the first record in case there are any records at all. The EOF is a Boolean property that is true if the current record is the last. It is also true if there are no records in the RecordSet. Then we make the program add the "Name" field of all records to the list box by adding the current records field "Name" and moving to the next record. You ask for a field of a RecordSet by putting a ! between the name of the RecordSet object and the name of the field. The while loop checks to see if there are more records to add.

Вам также может понравиться