Welcome, Guest: Join Nairaland / LOGIN! / Trending / Recent / New
Stats: 2,744,924 members, 6,512,467 topics. Date: Tuesday, 28 September 2021 at 11:12 PM

Daily Tutorial On Programming - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Daily Tutorial On Programming (513 Views)

Tutorial On How To Create A Blog - Start To Finish / Tutorial On: How To Build Php & Mysql Cms Website From Scratch / Video Tutorials On Programming, Webdesign, Graphics Design Etc (2) (3) (4)

(1) (Reply) (Go Down)

Daily Tutorial On Programming by CORELDRAW(m): 7:42pm On Nov 25, 2014
I will be sharing tutorial tips on programming. i hope this can help the newly admitted students into the Computer Science department get themselves familiarise with the programming aspect of the course. Also, the already programmers build there skills the more and avenue to ask various questions. I wouldnt be able to paste the screenshots and download forms here bt i hope you can always get it from the links i will be droping along.
in the next couple of days i will be dropping tutorial tips on VB6.0
All that is required is your laptop, VB compiler, and your subscription to get the daily tips
This tutorial is totally free, i promise
Thanks and keep following!
Great Naccosite!!
Re: Daily Tutorial On Programming by CORELDRAW(m): 7:45pm On Nov 25, 2014
Getting Started

LESSON 1 - Getting started
Defining basic terms
An application is a collection of objects that work together to accomplish something useful. In VB the application is called a Project. A Project could be a the management of a Video store, the calculation of mortgages, a dating service or the Payroll for 1000 employees ...
An object is a piece of software that has properties and functions that can be manipulated. Whew! You're here so, you must be somewhat familiar with the Windows environment. A window is an object. It has properties: size, color, position on the screen, etc. (The purists among you may want to talk about a class rather than an object but, at this point we just want to keep it simple, and the underlying concept is the same). The window has functions, also called methods that can be manipulated: change the size, move it around, open it and close it. You do not have to write code to resize a window - you just click and drag. But somebody had to write code at some point. Fortunately for us, when they did they put it all in a nice little package and called it a window object. Now, whenever you need a window in your Project you can make a copy of the window object, change its properties for color or size very easily, and paste it where you want it. Then you can use its built-in methods to open it, close it when you want or resize it whenever necessary. When you create an application using objects and combining them to produce results, you are working in an object-oriented environment.

To produce an application in COBOL, a procedural language, you write COBOL source programs, you compile them into machine code and then you run them via a control interface such as JCL. A program can contain 1000's of lines of source code and could run for hours with no human intervention. In fact, in large installations, a jobstream can consist of a dozen programs, all automatically accepting input from the previous program and producing output for the next. The programmer can be blissfully unaware that the program has run unless something catastrophic happens.
In a VB project, the processes that occur have to be associated with events. An event is something that happens - the user clicks on a button, a form is opened, the result of a calculation is too large. The operation is event-driven because everything that executes does so as the result of some kind of event. The role of the programmer is to anticipate the events and to write the code that will be executed when the event occurs. A VB application is interactive in the sense that the user is constantly interacting with the program. The user inputs a Customer Id, the program checks the Id in the database and immediately brings up the customer's file or displays a message that the particular Id is invalid.

Jumping right in!
Project description
We want to create a Scoreboard for a football game (there it is already!) between the Giants and the Redskins. To begin with the simplest task we will only count the touchdowns and display appropriate messages.
Please note: although we will create a complete functional Project with controls and code and so on, the purpose of this exercise is to show what can be done. In the following lessons we will be explaining scripts and the use of controls in a lot more detail. If you study this example you should be able to relate it to what you already know of programming and judge whether this tutorial will be easy or hard for you to do.

Creating the Project
First thing to do is to create a Directory where you will store all your VB Projects. Call it VBApps, for example. Then start VB. The first screen will ask whether you want to open a new project or an existing one - it's obviously a new one and it will be a Standard EXE. Then, maximize all the windows (it's easier to work with - some of the examples in the tutorial had to be reduced for the sake of the presentation). Now, save your project. It will first ask you to save the form - call it Score.frm - and then the Project - call it Scorebrd.vbp. From now on, do File-->Save Project very, very frequently.
Before you start to build-up the form, it will make it easier if you change the color of the form. Otherwise you will be working with grey controls on a grey background. To change the color, just click anywhere on the form, go to the properties window, find the property called BackColor and change it to the standard Window background (teal) or to any color you want in the palette.

In our first example we will need 6 labels and 2 command buttons. Each one of these objects that you put on a Form is called a control. To get a control you go to the Toolbox, click on the control you want, come back to the Form and click and drag the control to the size and position you want. Position the controls somewhat like in the diagram below.

IMPORTANT NOTE: If this is your first experience with VB, don't be afraid to experiment. This is hands-on stuff! Remember that VB is a Microsoft product, therefore it works with the standard Windows interface. All the functions you know from MS-Office work the same way here: Copy, Cut, Paste, (Ctrl)+(Click), (Shift)+(Click), drag the mouse over a group of controls to select them all, etc. The Undo button is a nice one to keep handy - when you modify a control you can always Undo the change - remember this when you get to the part about aligning the controls, making them all the same size and so on. That part can get tricky. If you accidentally end up in the Code window while playing around, go down a few paragraphs and you will see how to get back to the Form. At this point the worst that can happen is that your Form will get all messed up. So what! You can just scrap it and start over again, but you will have learned something.

Now that we have a bunch of controls on the form, we have to jazz them up a bit. We do this by changing the Properties of the controls in the Properties window. Each control has a whole series of properties, most of which we won't need right now. The ones we do need are:
Alignment = how text aligns in the control
BackColor = choose the color of the background
Caption = the text that will appear in the control
Font = choose the font type and size
ForeColor = choose the color of the text (foreground)
As with all Windows applications, you can select multiple controls with (Ctrl)+(Click) and change a property for all of them at once. For example, if all backgrounds are white, select all controls, change ForeColor to white and all of them are modified. Change your form to look like the one below. Note that you do not have to change the Caption for Label4, Label5 and Label6 and that you can't change the color of the buttons. They insist on being what was called in the old days "IBM grey". Don't forget to save your project often as you go along!
If you Run the application at this point, you should see your Form appear, just the way you created it. However if you click on any of the controls, absolutely nothing happens! There are events that occur; the form opens, a button is clicked, etc. But, there is nothing that tells the form what to do when it sees an event. That is why we have to write code, also called script.

To switch between the Code window and the Form window, use the buttons just over the Project Explorer window (diagram on the left).
Once in the Code window, you have the option of seeing all the code for the Project or the code for one event at a time. Use the buttons in the lower left-hand corner (diagram on the right).
To select the object and the event you wish to code, use the two Listboxes at the top of the Code window. The one on the left for the object and the one on the right for the event. Start with General ... Declarations and then Form ... Load, etc.

At this point you might want to download the sample program and study it. In the following lessons we'll add functionality to the exercice and we'll explain what the code means. But for the moment, a good exercice would be to write part of the code and then try to figure out how to improve certain aspects of the program.

You can download the application here: FootScoreboard.zip

Now we can Run it and see something happen. When the Form loads, it will initialize the fields that we specified in the code.

Now code the Command1 button and Run it to see the result.

Re: Daily Tutorial On Programming by CORELDRAW(m): 9:45am On Nov 28, 2014
Writing Code

LESSON 2 - Writing code

The Code Editor
As we saw in the previous lesson, getting to the Code Editor is as simple as hitting the proper button. You may have discovered that you can also call-up the Editor by double-clicking on an object. It is also possible to select "View code" with the right mouse button. You will note that the Editor has all the functions of a text editor and then some. The most commonly used functions will be Cut ... Copy ... Paste which you can call from the Menu, from the Toolbar or from the right mouse button. You also have access to the usual Find and Replace functions.
Getting help
There is a lot of documentation available on VB. There is so much, in fact, that it's easy to get lost in it. However, the on-line Help available from the Menu should be used regularly. Very often just doing a search on a word in particular will be sufficient to get you out of a jam. If you want to go into more detail check out the Contents part of MSDN (Microsoft Developers' Network) and surf through it.
Writing code
VB is not very particular about presentation - spaces, indents, lower case or upper case, it doesn't make too much difference to the compiler. But it may make a whole lot of difference to the programmer who has to maintain your code in 2 years, after you've moved up to President.
Apply "Best Programming Practices"
When you work with RAD (Rapid Application Development) tools like VB in a graphical interface environment, you become more than just a programmer, a writer of code. You are a developer. We will cover that in the next lesson.

But at the moment, you are still a Programmer. And unless you are developing an application for your own personal use, that nobody else will see, you have to think of the environment, of the team you are working with.
"No man (or woman) is an island!"
Especially when it comes to programming. The code you write may have to be checked by an Analyst. It will have to go through testing. It may have to be modified by other team members and it almost certainly will go through modifications, maybe several times, in the months and years ahead when you probably won't be around to defend yourself. "The evil that men do lives after them...". You do not write code for the VB compiler. You write it for other developers and programmers. What you want others to say behind your back is: "That Jane was blindingly efficient, brilliant, a genius with comments ...". You do not want to be remembered as "...the Picasso of code, master of the abstract".
If you are just starting out with the language, why not pick up a few good habits right now and it may make your life a lot easier down the road.

Use comments when appropriate but not so many as to overwhelm the code; the apostrophe ' is the comment identifier; it can be at the beginning of a line or after the code.

' This is a comment
'on 2 lines
DIM intNumber AS Integer 'This is a comment

Use indents - code must be indented under control structures such as If ... Then or Sub - it makes it so much easier to follow the logic.

FOR i = 1 TO 5
value(i) = 0 ' Indent used in control structures

Use standard capitalization - keywords like If, Dim, Option, Private start with a capital letter with the rest in lower case; variable names, control names, etc. are usually mixed case: ClientName, StudentId, etc.
Write extra-long statements on 2 lines using the continuation character _ (space underscore); in VB each line is assumed to be an individual statement unless there is a continuation at the end of the first line.

Data1.RecordSource = _
"Select * From Titles" ' One statement on 2 lines is OK

Naming conventions
These are the rules to follow when naming elements in VB - variables, constants, controls, procedures, and so on:

A name must begin with a letter.
May be as much as 255 characters long (but don't forget that somebody has to type the stuff!).
Must not contain a space or an embedded period or type-declaration characters used to specify a data type ; these are ! # % $ & @
Must not be a reserved word (that is part of the code, like Option, for example).
The dash, although legal, should be avoided because it may be confused with the minus sign. Instead of Family-name use Family_name or FamilyName.

Data types
Data type

Storage size


1 byte

0 to 255

2 bytes

True or False

2 bytes

-32,768 to 32,767
Long (long integer)

4 bytes

-2,147,483,648 to 2,147,483,647
Single (single-precision floating-point)

4 bytes

-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
Double (double-precision floating-point)

8 bytes

-1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Currency (scaled integer)

8 bytes

-922,337,203,685,477.5808 to 922,337,203,685,477.5807

14 bytes

+/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001

8 bytes

January 1, 100 to December 31, 9999

4 bytes

Any Object reference
String (variable-length)

10 bytes + string length

0 to approximately 2 billion
String (fixed-length)

Length of string

1 to approximately 65,400
Variant (with numbers)

16 bytes

Any numeric value up to the range of a Double
Variant (with characters)

22 bytes + string length

Same range as for variable-length String
User-defined (using Type)

Number required by elements

The range of each element is the same as the range of its data type.

In all probability, in 90% of your applications you will use at most six types: String, Integer, Long, Single, Boolean and Date. The Variant type is often used automatically when type is not important. A Variant-type field can contain text or numbers, depending on the data that is actually entered. It is flexible but it is not very efficient in terms of storage.
Declaring variables
Declaring a variable means giving it a name, a data type and sometimes an initial value. The declaration can be explicit or implicit.

An explicit declaration: variable is declared in the Declarations Section or at the beginning of a Procedure. An explicit declaration looks like:
Dim MyNumber As Integer

Now the variable MyNumber exists and a 2-byte space has been reserved for it.

An implicit declaration: the variable is declared "on the fly", its data type is deduced from other variables. For example:
Dim Total1 As Integer 'Explicit declaration
Dim Total2 As Integer 'Explicit declaration
Total3 = Total1 + Total2 'Implicit declaration
Total3 is not formally declared but is implied, it is "arrived at" from the other declarations.

It is never a good idea to have implicit declarations. It goes against the rules for clarity, readability and ease of use of the code.
To make sure that this rule is followed, start the Declarations with the Option Explicit clause. This tells the compiler to consider implicit declarations as errors and forces the programmer to declare everything explicitly.

Other examples of declarations:
Dim MyName As String
Dim StudentDOB As Date
Dim Amount5, Amount6, Amount7

In the last example the type assigned to each variable will be: Variant. It is the default type when none is specified.

There can be multiple explicit declarations in a statement:
Dim EmpName As String, SalaryMonth As Currency, SalaryYear As Currency

In this final example, what are the types assigned to the three variables:
Dim Amount1, Amount2, Amount3 As Single

All Single-precision floating point, you say. Wrong! Only Amount3 is Single. Amount1 and Amount2 are considered Variant because VB specifies that each variable in a statement must be explicitly declared. Thus Amount1 and Amount2 take the default data type. This is different from what most other languages do.
A constant is a value that does not change during the execution of a procedure. The constant is defined with:
Const ValuePi = 3.1416

The Scope of variables
The term Scope refers to whether the variable is available outside the procedure in which it appears. The scope is procedure-level or module-level.

A variable declared with Dim at the beginning of a procedure is only available in that procedure. When the procedure ends, the variable disappears. Consider the following example:
Option Explicit
Dim Total2 As Integer

Private Sub Command1_Click ()
Dim Total1 As Integer
Static Total3 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub

Private Sub Command2_Click ()
Dim Total1 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub

Every time Button1 is clicked, Total1 is declared as a new variable during the execution of that clicked event. It is a procedure-level variable. It will always stay at 1. The same for the Button2 event: Total1 is a new variable in that procedure. When the procedure ends, Total1 disappears.
Total2 is declared in the Declarations section. It is a module-level variable, meaning it is available to every control in this Form. When Button1 is clicked, it increments by 1 and it retains that value. When Button2 is clicked, Total2 is incremented from its previous value, even if it came from the Button1 event.
Total3 shows another way of retaining the value of a local variable. By declaring it with Static instead of Dim, the variable acts like a module-level variable, although it is declared in a procedure.

Another scope indicator that you will see when you study examples of code is Private and Public. This determines whether a procedure is available only in this Form (module) or if it is available to any module in the application. For now, we will work only with Private procedures.
Mathematical and Text operators




Exponent (power of)

4 ^ 2



5 * 4



20 / 4



3 + 4



7 - 3


Remainder of division

20 Mod 6


Integer division

20 \ 6


String concatenation

"Joan" & " " & "Smith"

"Joan Smith"

Note that the order of operators is determined by the usual rules in programming. When a statement includes multiple operations the order of operations is:
Parentheses ( ), ^, *, /, \, Mod, +, -
Logical operators




Equal to

9 = 11


Greater than

11 > 9


Less than

11 < 9


Greater or equal

15 >= 15


Less or equal

9 <= 15


Not equal

9 <> 9


Logical AND

(9 = 9) AND (7 = 6)


Logical OR

(9 = 9) OR (7 = 6)


Control Structures
If condition1 Then
End If

If condition1 is True, then statements1 block is executed; Else, condition1 is not True, therefore statements2 block gets executed. The structure must be terminated with the End If statement.

The Else clause is optional. In a simple comparison, statements1 get executed or not.

If condition1 Then
End If
Select Case
Can be used as an alternative to the If...Then...Else structure, especially when many comparisons are involved.

Select Case ShirtSize
Case 1
SizeName.Caption = "Small"
Case 2
SizeName.Caption = "Medium"
Case 3
SizeName.Caption = "Large"
Case 4
SizeName.Caption = "Extra Large"
Case Else
SizeName.Caption = "Unknown size"
End Select
Used to execute a block of statements in an unspecified number of times.

Do while condition

first, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed.
When the number of iterations of the loop is known, it is better to use the For...Next rather than the Do...Loop.

For counter = start To end

1) The counter is set to the value of start.
2) Counter is checked to see if it is greater than end; if yes, control passes to the statement after the Next; if not the statements are executed.
3) At Next, counter is incremented and goes back to step 2).

More will be covered on Control structures as it becomes necessary in upcoming lessons. Meanwhile, if you want to know more, consult the VB Language Reference.

For additional resources you might find this site useful: Free Visual Basic 6 tutorials and source code examples
To practise your coding and editing skills, try modifying the Football example by adapting it for different sports. For example, in American football, which is similar to rugby, there are 4 different ways to score, as shown here:


6 points
Field goal

3 points
2-point Convert or Safety

2 points

1 point

Re: Daily Tutorial On Programming by CORELDRAW(m): 12:16am On Dec 06, 2014
Designing the Application

LESSON 3 - Designing the application
Starting the process

when you start to work on a VB Project you are no longer just a programmer - you are now a developer. You will have to get much more involved in the whole design process. Unless you are designing an application for your own use you will have to work with a team of specialists including, but not limited to, users, analysts, GUI designer, programmers, testers, network specialist, webmaster and marketing people. The whole process is iterative - do part of it, check it, get input, go back and correct it, do the next part, and so on. Nobody expects you to do a whole project in one fell swoop - it would probably be a disaster if you did do it that way.
The importance of Users
Any project that you develop has to involve Users. They are the people who will sit in front of your interface for eight hours a day and decide if they like it or not. If they don't like it, no matter how efficient the code and how many millions of dollars were spent developing it, they will find ways to sabotage it.

Get users involved from the start. If you are developing a product to specs, that is to be sold to some client eventually, there has to be someone who knows what that eventual client needs. Find a typical user of the product to use as a sounding board. Remember: you are just the developer; no matter how cool you think it would be to use all purple text on orange backgrounds, it is the user who will tell you what is cool and what is not. As you develop more and more parts of the application, run them by the user to check for accuracy, completeness, clarity, etc.

Here's an example of how to design for clarity. Given that 01/02/03 is a date, what date is it? If you are an American, you probably automatically assume that it is January 2nd, 2003. If your user is French, however, he would assume that it is February 1st, 2003. And if you are working with this Professor, who has a very definite opinion on the subject, he would say that it is February 3rd, 2001 and should always be written as 2001-02-03. If all your forms are designed as: "Enter date" with a blank box beside it, you are headed for trouble.

Program design today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
-- Rich Cook

That's just a joke, by the way. Most users are not idiots. Sometimes they appear confused because they are trying to solve the problem and they can't figure out how. But that's not their job. Their job is to explain clearly what it is they need. Your job is to figure out how to provide it. Don't underestimate users. Be patient, be understanding without being condescending and be humble. There's a lot of things that the user knows how to do that you don't.

Creating the User Interface
The user interface that you design is the most visible and perhaps the most important part of the application. The term commonly used for this type of interface is: GUI (Graphical User Interface). It's pronounced "goo-wee", not "guy". It is graphical because it consists of buttons, menus, icons, etc. An example of a non-GUI is DOS (remember that?) where everything is text. User interface refers to the fact that it is the part of the application between the user, in front of the screen, and the code behind the screen. How well the user can interact with the code depends on the quality of the interface.
Guiding principles

The user is in control. The user must feel he is in charge of the application. He must have a certain amount of control over such things as window size, window position, choice of fonts, etc. There should definitely be a "Preferences" item in the menu.
Consistency is maintained throughout the application. The user can move to any part of the application and not have to re-learn how things work. Consistency in the choice of icons, in date formats, in error messages means that the user can concentrate on the work. As much as possible, the application should be consistent with Windows standard. For example, "Move to the Recycle Bin" is different from "Delete" - the user has come to expect that an item in the Recycle Bin can be recovered if need be.
Application should be "forgiving", or "fault-tolerant". Users will make mistake. A single error should not bring the application crashing to the floor. If there is no room for errors, users will be afraid to experiment, to discover on their own how to do things. It will slow the learning process considerably.
Always supply feedback. The user should always know that something is going on, especially if it's in the background and may take several minutes to run. Display an hourglass or a progress meter or a status bar so that the user doesn't start to hit keys at random to get something to happen. It only takes a few seconds of inactivity for the user to get frustrated and think that the program is "hanging".
Don't neglect aesthetics. The visual aspect is important. The environment should be pleasing to the eye. The presentation style should help in understanding the information presented.
Interface should be simple without being simplistic. There should be a balance between simplicity and functionality. Popup menus, for example, allow you to increase the functionality without having to encumber the screen with all kinds of details which are not used 95% of the time.

On the importance of language

Throughout the project you are going to be doing, you should give some thought to the quality of the language used. As a teacher of technology, I am constantly defending the compulsory language courses included in the curriculum. I have to point out that your mastery of the language, or lack thereof, projects an image of who and what you are. This is the 21st Century - image is everything!

When I was young, a long, long time ago, in a galaxy far, far away, teachers used to say all the time: "Sloppy work is the sign of a sloppy mind!". There is a lot of truth in that. If you can't be bothered to display the interface correctly, what does that say about the rest of your work? Professionalism should be evident in every part of what you create. If what is seen by the public is of poor quality, there is reason to believe that the work behind the interface (90% of the application) is also poor.

If you are developing an application for yourself, nobody cares what it looks like. If it's a small project for a client that you know, you may be able to get away with some mistakes. Usually however, a project is broader in scope and you don't know the audience. Remember that you are now working in the global village. The interface you write and display may be seen, via the Internet, by millions and millions of critical users. Even if it's not your reputation riding on it, the reputation of your client may be. And you can be sure that he will take it seriously, even if you don't. If language is not your area of expertise, get help from somebody whose area it is.

Having said all that, I realize that I am really sticking my neck out. Although every effort has been made to make these tutorials as error-free as possible, it is inevitable that some mistakes will slip through. You are allowed to say, "Gotcha!" when you spot mistakes. Accept my apology and I will correct all errors as soon as they are spotted.
To err is human.
But it takes the Web to let millions of people know that you erred!
Interface style
One of the first decisions you have to make is whether to go SDI (Single Document Interface) or MDI (Multiple Document Interface). If you have worked with Windows for any length of time, you have probably seen both. Notepad is an SDI - you can only have one document open at any time. Word is an MDI - you can open a number of documents and switch between them at will. An MDI application imposes different constraints on the developer because of the need to juggle several different forms at the same time. It usually requires more experience in the development process. For the purposes of this tutorial, we will work only with SDI applications.
Design considerations

What is the purpose of the application? Is it a once-a-year thing or one that is in use 24/7? The user will forget the details if he only uses it once a year and you will have to be a lot more specific with the Help functions.
Who is the intended audience? Beginning users will need more directions than experienced users.
How many different forms will be needed (you can have several forms without being MDI) and how will they be connected?
What are the menus going to say? Will toolbars be used to replicate menu functions?
How are errors going to be identified to the user? How will they be corrected?
How much Help (in the form of a Help function) is going to be provided?
How will consistency be maintained across the application? It is important that all forms have the same "look and feel" in terms of colors, fonts, menus, toolbars, etc.

We will examine the design process in more detail as we develop the Projects in the following lessons. If you are serious about the design aspect of software, one of the best sources of information is the book: "The Windows Interface Guidelines for Software Design" published by Microsoft Press, reference ISBN 1-55615-679-0.

Re: Daily Tutorial On Programming by CORELDRAW(m): 12:17am On Dec 08, 2014
LESSON 4 - Standard controls

For this lesson we will need a new Project, call it Lesson4.vbp, which will only be used to create and try out various controls.

To refresh your memory, since the previous two lessons have been rather theoretical, you select the New tab, and Standard EXE for the type. As soon as The Form opens, you Save the new Project, give the Form a name, let's say it's Lesson4.frm and then you give the Project a name: Lesson4.vbp. Note that you do not have to specify the extensions, .frm and .vbp, because they will be assigned automatically.
The Form

We covered it too briefly in Lesson 01 so we'll go over it again.

The Form is the first object you see when you Open the application. It's the window into which all the controls will appear, where you will input data and see results.

There's not too much you can do with the form at this time. Basically, you adjust the BackColor and the StartUpPosition (where it will open on the screen when you Run it) and then you start putting controls on it.

The Label

This is probably the first control you will master. It is used to display static text, titles and screen output from operations. The important properties to remember:

Caption - the text that is displayed in the label
BackColor and ForeColor - colors of the background and the text
BackStyle - Opaque or Transparent - whether the background is visible or not
Font - font and size of text
Alignment - text centered, left or right
Multiline- True or False - if True, you can have several lines of text, delimited by <CR> in the label - by default, it is set to False

Frame & PictureBox

When you want to group several controls together - name and address, for example - you use a Frame. The frame backcolor can be the same as the form's and only the frame borders will be obvious, or it can be a different color and stand out.

You create the frame before the controls. When you create controls in a frame, they are tied to the frame and move with it. The frame caption is the text that appears at the top of the frame - you use it to define the group.

The PictureBox is like a Label with a picture in it instead of text. The Picture property determines the name of the file, .BMP or .GIF, that will be displayed. It can be used for a company logo, etc.


TextBox & CommandButton

The TextBox is like a Label but, it is used to input data into the program. The data typed in is in the Text property of the control.

When the program is Run, only the controls that can be manipulated will be activated. For example, if the form contains 3 Labels, 3 TextBoxes and 3 Buttons, when it is Run, the cursor will not stop at the labels.

When the user hits the Tab key, the cursor will go to the first TextBox or Button - not necessarily the first one on the form but, the first one that was created. That is called the Tab order and you have to specify it.

On the form there is only one control at any given time that has the cursor on it - it is said to have Focus. If you type data, the control with Focus will receive it. You change the Focus with Tab or by clicking on a different control.

Up until now we haven't bothered with the names of controls (the Name property). Once we start to code, however, it does become important. There are all kinds of occasions in code where you have to call upon a certain control. It can get very confusing when your 12 buttons are called Command1...Command12. What did Command7 do, again? Give each control a name (except for titles, etc. that you never refer to) so that you will be able to identify it easily. It is recommended that you use a prefix when assigning a name; cmd for a CommandButton, lbl for a Label, txt for a TextBox. Thus, txtNumber where you input the value can be distinguished from lblNumber where you display the result.

The CommandButton is used to initiate actions, usually by clicking on it. The Caption property determines the text to display on the face of the button. The Default property, if set to true, means that the button will be activated (same as Clicked) if the <Enter> key is hit anywhere in the form. If Cancel is set to True, the button will be activated from anywhere in the form by the <Esc> key.

Hopefully, you have now run this program several times, each time you added a new control, in fact. Admittedly, nothing much happened except to confirm that the controls were appearing in the right place on the form.

Here now is an example of the code we could write to perform simple tasks: input name and city and display the information in a label when the Continue button is clicked. The Exit button will end execution of the program and the Cancel button (or the Esc key) will clear the fields.

A few explanations: the Form_Load event occurs when the form first opens. This is where we initialize things - we want the TextBoxes and the result Label to be empty when we start off so, we set them to a blank space.

The actual processing is done after the data have been entered and we hit the Continue button. The processing logic is put in the Continue_button_clicked event.

When you hit the <Esc> key or you click on the Cancel button, you want to annul the entry you're doing and start over again. That's the same as opening the form so, we just tell the program to execute the Form_Load procedure which we already have.

The Exit button uses the pronoun Me to Unload. Me means the form currently active without having to name it.


Multiple forms

For the next series of examples we will use a new Form. It is not necessary to create a new Project; any Project can have several Forms in it.

With the Project open on the current Form, go to: Menu --> Project --> Add form. Select New form in the creation window and, voila! Next time you save the Project, it will ask you to name this new Form. You can name it Lesson4B.frm for example.

One more detail: when you Run the Project, you want to tell it which Form to open.

Go to the Project Manager window, right click on the Project name and select Project properties. In the Project properties window, the ListBox on the right says "Startup object". Select the Form you want to open when you Run. You can change the Startup object at any time to run the different forms that you created.

Check boxes & Option buttons

These two controls are used when the user must choose from a list of options. The difference between the two is that with Check boxes he can select several at one time but, with Option buttons, he must select only one among several.

The example below illustrates the use of Check boxes and Option buttons. To capture the information entered by means of these controls, you must test the property: Value. In a Check box, Value = 1 if box is checked and = 0 if not. In an Option button, Value = True if selected and = False if not.

The code, although somewhat long, is not very complicated. Most of the time, processing consists of checking the content of .Value. It is fairly standard procedure, especially with Option buttons, to ensure that at least one button has been selected and to display an error message if it has not.

Assignment 3

Create the Payroll form shown below. Number of hours must be entered as well as the appropriate rate. Gross salary = rate * hours. Net salary = gross salary - deductions.

Look at "Lesson 11 - Downloads" for the solution.


(1) (Reply)

15 Minute Micro Job For Webmaster / URGENT: Quote For Custom Forum Design / Re-design Naijaidol.com

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2021 Oluwaseun Osewa. All rights reserved. See How To Advertise. 417
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.