Monday, January 18, 2010

Number Validation in Vb 6.0

How to validate number with IsNumeric Function?


Input from user must be validated before it is accepted and stored into the database table. For validating number visual basic provides 'IsNumeric' Function that takes the string as input parameter. The return value of this function is a boolean value either True or False.

Often the text box input values are checked for validation. If you have a text box named txtAmount for input of currency amount then you can validate it in the text box's Validate event.

I will explain number validation in VB 6.0 with an example. Create a standard EXE project in Visual Basic IDE. Put a text box and set its name property to txtAmount. Put a command button and set its name property to cmdValidate. In the Validate Event of the text box write the following code.


Private Sub txtAmount_Validate(Cancel As Boolean)
If Not IsNumeric(txtAmount.Text) Then
Cancel = True
MsgBox "Enter valid Amount", vbExclamation
txtAmount.Text = ""
End If
End Sub

In the command buttons click event write the following code,

Private Sub cmdValidate_Click()
MsgBox "Valid amount"
End Sub

The output for different inputs are as under,

Date validation in VB 6.0

How Date Validation is done with IsDate Function?


You can easily validate the Input of date using IsDate function. The function will return a boolean value indicating the true or false result. Date validation is essential in every commercial / business application. In VB .NET you can use DateTime.Parse() method in a try catch block. If the date is not valid the catch block will execute where you can handle the error condition. In VB 6.0 you can use the IsDate() Function with the date string as input parameter.

Here is an example tutorial for IsDate function. Create a standard EXE project and put a text box name txtDate. Put a command button name cmdValidate. In the Validate event of txtDate write the following code.

Private Sub txtDate_Validate(Cancel As Boolean)
If Not IsDate(txtDate.Text) Then
Cancel = True
MsgBox "Enter valid Date", vbExclamation
txtDate.Text = ""
End If
End Sub

Friday, January 15, 2010

Vb 6.0 Registry Tutorial

How to access System registry? - An example


In windows operating system 'Registry' is an essential and critical system component in which windows stores application and user settings and preferences. For example if you want and application to run when you start windows you can instruct it in the registry in the following registry path,

\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

HKEY_CURRENT_USER stores user specific information. Applications can store user specific preferences and application states in this part.

In Visual Basic we have two functions, SaveSetting and GetSetting to Save the setting and get the setting from the registry. The settings will be saved in the following registry path: \HKEY_CURRENT_USER\Software\VB and VBA Program Settings.

The syntax of the GetSetting function is,

GetSetting (AppName as String, Section as String, Key as String, [Default]) as string

Where AppName is the application name, section is the registry section, key is the String/Binary/DWORD value.

The following tutorial will demonstrate the SaveSetting and GetSetting functions in VB 6.0

Open VB and create a Standard EXE project. Put a command button and set its name property to cmdSave and its caption property to save. Put a text box on the form and set its name property to txtSetting. Put another command button and set it's name property to cmdRead.

Double click cmdSave and write the following code,

Private Sub cmdSave_Click()
SaveSetting App.Title, "Example", "Test", txtSetting.Text
End Sub

Double click cmdRead and write the following code,

Private Sub cmdRead_Click()
MsgBox GetSetting(App.Title, "Example", "Test", "")
End Sub

Open the registry with regedit to see the results.

I have given Application Name / Title as 'RegistryDemo'. That is used as root entry for our application in VB and VBA program settings. "Example" is my setting entry or folder. Test is my key name with value 1234.









VB 6.0 offers only basic registry editing functions. If you want to perform advanced registry operation you must use Win32 registry functions which are more powerful. In VB .NET there is separate namespace with classes for registry editing.

InputBox example in VB 6.0

What is inputbox? Input Box Tutorial


Inputbox function in Vb 6 is used to receive input from user. A Dialog box prompt will appear on the screen asking for the text input. The input is one line in size. You can type any data as string. Date, Time, Numeric values, Character Data. The maximum acceptable length of the string is 254. This is the syntax of the InputBox funtion.

InputBox(Prompt, [Title], [Default], [XPos], [YPos], [HelpFile], [Context]) as string

'Prompt' is the Descriptive text on the inputbox. 'Title' appears on the Windows Title Bar. 'Default' is the InputBox Default Value. Xpos is the X co-ordinate position in twips. YPos is the Y Coordinate position in twips.

Here is the example of typical Inputbox. This small tutorial will help you understand the usage of InputBox

Create a Standard Exe project and put a command button and set its name property to cmdGetAge. Double click the button and write the following code.

Private Sub cmdGetAge_Click()
    Dim Age
    Age = InputBox("Enter your age", "Your Age", 20, 100, 100)
    MsgBox ("The age is: " + Age)
End Sub

Press F5 to run the project and click the button.


Tuesday, January 12, 2010

VB Source Code for Departmental Stores

Case Study - Departmental store project in VB



Visual Basic is is the ideal development environment for business applications like Departmental Stores. What are the basic operations in system involved in a Departmental Store? They are traders. They purchase goods from whole sellers and sell the items with a marginal profit. The purpose or goal for the software system is to assist the management in assessing profit / loss to make financial decisions, to streamline the inventory / stores operations, purchase decisions etc. Making electronic billing is another necessity. In large departmental stores there may be many billing counters catering the needs of hundreds of customers.

So the major modules are Purchase Orders, Purchase, Purchase Returns, Sales, Sales Returns.

Everything starts with making purchases. Since there is no manufacturing in departmental store all goods are purchased. There are multiple suppliers for different items. Purchase manager will get quotations from multiple suppliers and make final decisions. After authorization from finance/accounts department he will make purchase orders.

Before writing code, we need to design our database. First we need to select our back-end or database server. For small stores with single user environment MS-Access database is enough. But for large stores with huge volume of data Microsoft SQL Server or Oracle Database server is needed. It depends on the requirement and need. After selecting the database design the tables, primary key and relations. One to many relationships will be there in Master detail tables.

Consider Purchase Order. To make a purchase order we need to store supplier details, Purchase order number, Date etc. And we need to store Products/ items, their quantity, rate and amount. So we will create two tables, one for the master details like supplier details which will fit in one record. For Detail part there are as many record as the number of items / products. The primary key is the Purchase order Number.

In this fashion design tables for Purchase Inwards (Goods Received), Purchase Return, Sales, Sales Return.

Separate tables are needed for Master details like Prouducts, Suppliers.

After creating tables design forms in VB. The master details will fit in textbox, DateTime picker. The details will fit in a FlexGrid control. FlexGrid is the activex control with excel like cells with rows and columns.

Billing is done with Products BAR code details. A barcode scanner will scan the BAR code printed on the product. The scanner is linked with the computer system via a Serial communication port or USB port. To read the serial port you can use MSComm Activex control in Visual Basic. I have covered Com Port Tutorial in another post. The BAR CODE is equivalent to a product number stored in product database. So you can retrieve the amount / rate of the product using a database query.

Thus you have completed the Billing part. Normally bills/invoices are printed on Dot-Matrix printers. For fast printing use Direct Port Printing. The Printer object in VB will be slow as it prints in Graphics mode. The text mode printing can be achieved by using Win32 Printer APIs or Direct Port Printing. Use File IO and specify "LPT1" or "PRN" as file name and when you flush the file it will be printed.

Reporting can be done using Crystal Reports. There can be no readymade solution for Departmental Stores or other retail business. Each business is unique and have specific requirement. So a custom made software is necessary. You can tailor the existing programs to suit your needs. I have developed many such applications of Departmental Stores, Hardware Stores, Retail Chains, Medical Shops, Restaurants and more.

Write to me if you want my assistance. You can hire me at a reasonable price.

My email: sundaracm@gmail.com

Monday, January 11, 2010

Timer Control in Vb6

What is a timer control



A timer is a timer. You can place a timer control and give an interval in milliseconds. After the lapse of specified interval timer's Timer() event will fire. You can write code in this block. In other words if you want to execute a certain code at certain interval you can use timer on a windows form. The timer event will continue to fire unless you change the Timer's enabled property to False.

Now we will see the timer functionality with an example tutorial. In this tutorial we will put a timer control on a windows form to display current date and time.

Timer Tutorial Project

Create a standard EXE project and put a Timer control on the form. Set its name to tmrTime. Set the Timer's Enabled property to True. Set the interval property to 1000 (milliseconds). Place a label control on the form and set it's Name property to lblDate. Put another label control and set its name property to lblTime.

Double click the Timer control and write the following code,

Private Sub tmrTime_Timer()
lblDate.Caption = Date
lblTime.Caption = Time()
End Sub

You can format the Date Time as per your requirement. For Date Formatting,
use Format(Date,"dd-MMMM-yy" ) to display date in day-month-year format.

To format Time use, Format(Time(),"hh:mm AMPM") will display hour:minute AM/PM

Run the project by pressing F5 key


Hurray! You have created a simple project to display current date and time.

Sunday, January 10, 2010

MDI form Tutorial in VB

MDI form Tutorial in VB 6.0


MDI or Multiple Document Interface is the container form of child form. In visual basic MDI form has special meaning. This type of form is parent form of all other child forms. This form can not have normal VB controls like TextBox, Label etc. Instead you can add Menu, Status bar controls in MDI form. To add MDI form in Visual Basic go to Project -> Add MDI Form menu. This will add an MDI form. Only one MDI form can be added in a VB 6.0 project.

Normal Windows form is made an MDI child by setting its MDIChild property to True. When you make a form MDI child, its StartUpPosition can not be set to CenterScreen.

MDI forms supports some special properties, methods and events.

Arrange method: In windows application you might have noted a 'Window' menu with Arrange Icons, Cascade, Tile Horizontal and Tile Vertical sub menus. This will arragne the child windows accordingly. So you can call the arrange() method with the FormArrange Constants.

PrintForm, Pset and other normal form methods are not supported on MDI windows. Because no graphics drawing operation can be performed on the client area of the MDI window. You can only put a picturebox control inside the MDI form.

AutoShowChildren is specific property to MDI forms. This property Returns/sets a value (True/False) that determines whether MDI child forms are automatically displayed when loaded.

In short most application contain an MDI form that is place holder for other forms. With menu control on the top and status bar at the bottom.



ComboBox Control in VB 6

ComboBox in VB 6



Combobox is another popular VB control. It has a black downward arrow clicking which a drop down box is displayed with the content of the combo box. User can select a value of their choice.

The items in the combobox is selected using combobox.list(index). Current item can be selected by combobox.list(combobox.listindex), where the listindex property gives the index number of currently selected item.

You can make a combobox, databound using its datasource and datamember properties.

Adding Items:

At Run time: At runtime you can add items in a combobox control using it ComboBox.Add("item name") method.

At Design Time: Use ItemData property of the control to keyin the list of items.

Here is an example of combobox controls that is filled with three colors 'RED', 'GREEN' and 'BLUE'.

To repeat this tutorial create a new standard EXE project in VB 6. Add a Lable control and set its caption property to Colors. Add a ComboBox control and set its name property to cboColors. Add a Command Button and set its name property to cmdFill and caption property to Fill Items. Double click the command button. Add the following source code.

Private Sub cmdFill_Click()
cboColors.AddItem "RED"
cboColors.AddItem "GREEN"
cboColors.AddItem "BLUE"

End Sub

Add another command button and set is name property to cmdShow and caption to Show items. Double click the button. Add the following code.

Private Sub cmdShow_Click()
On Error GoTo Err:
If cboColors.ListIndex = -1 Then
MsgBox "Please select an item"
cboColors.SetFocus
Exit Sub
End If
MsgBox cboColors.List(cboColors.ListIndex)
Exit Sub
Err:
MsgBox Err.Description
End Sub

Run the project by pressing F5 and click Fill Items. Check the ComboBox to see the newly added items.

OptionButton control

What is OptionButton?


CheckBox control can select multiple controls. In contrast an OptionButton control is used for mutually exclusive selection. That means only one optionbutton can be selected at a time. For example the Gender / sex of a person is given using OptionButton. Only Male or Female can be selected. To offer several fields use them on a frame control.

The Value property of the optionbutton can be set to true or false. True means slected false means not selected. Style property can be used to set picture to the option button. Visible property can be set to true or false.

Appearance property Returns/sets whether or not the optionbutton is painted at run time with 3-D effects.

Caption property is used to set the Descriptive text on the control.

You can use Control Array option to give same name to multiple controls. In this case give the same name and VB will ask You already have a control name '---'. Do you want to create a control array? Give yes to create the control array. You can access the control by giving array index numbers.





CheckBox Control

What is a checkbox control in visual basic?



Checkbox control gives true or false type input. It offers a tick or untick option. The state of the control can be accessed by it Value property. It can be either Unchecked(0) or checked(1).

Visible property is used to show or hide the control on user screen. Style property can be Standard(0) or Graphical(1). Thus you can show picture on checkbox control using it picture property and set Style property to Graphical.

CheckBox also supports DataSource property. You can set a database field to a checkbox. It should be a Yes/No, True/False type field because the checkbox can accept only these two values.

Command Button Tutorial

Learn Basics of VB Command Button

Ok. You have received user input via TextBox, Radio button, check box, Combo box and list box control. Now you want to process the data and store it in the underlying database. So you give Command button to process the data. In business applications, Save, Delete, Update, Exit, Close commands are given using command buttons.

The frequently used property of command button is, Caption property which sets the descriptive text on the command button.

BackColor property sets the background colour of the command button. To enable this property the style property must be set to graphical. Otherwise this property will not work.

Style property Return/sets the appearance of the control, whether standard (standard Windows style) or graphical (with a custom picture).

DisabledPicture Returns/sets a graphic to be displayed when the button is disabled, if style is set to 1.

DownPicture Returns/sets a graphic to be displayed when the button is in the down position, if style is set to 1.

Visible property Returns/sets a value that determines whether an object is visible or hidden.

ToolTipText property Returns/sets the text displayed when the mouse is paused over the control.

TabStop Returns/sets a value indicating whether a user can use the TAB key to give the focus to an object.

Picture Property Returns/sets a graphic to be displayed in a command button, OptionButton or CheckBox control, if style is set to 1.

MaskColor property Returns or sets a color in a button's picture to be a 'mask', if style is set to 1.

SetFocus method is the common method of command button used to set focus on the control.

Click is the common event of command button control. Mouse click or keyboard's enter key fires this event.

GotFocus, LostFocue, KeyPress, KeyDown, KeyUp, MouseDown, MouseUp are some other events supported by Command button.

Frame (GroupBox ) Control

Learn about VB 6.0 Frame control



Frame control in Visual Basic 6.0 is used to group similar controls / controls of similar functionality together. In Visual Basic .NET this control is replaced by Group box control.

Caption Property the most commonly used Frame control property, which sets the frame's descriptive caption. Other common properties are BackColor, Forecolor, Font and Visible.


Saturday, January 9, 2010

TextBox control Tutorial

Textbox control for user input

TextBox is the widely used windows control in visual basic. No software application is possible without a text box. All string and numeric data is received via text box control. Whether it is a customer name, supplier name, age, amount, address or any other user data is retrieved through text box. Textbox is for basic text input without formatting. For formatted text (Font style, bold /italic, alignment options) we use RichTextBox control, an Activex control in VB 6.0. In .NET Richtextbox is an intrinsic control.



This tutorial will help you understand the Visual Basic TextBox control and its important properties, methods and events.

Name property: A unique name given to the textbox control on a windows Form. Usually 'txt' is the prefix used for textbox. For example, if you use a textbox to get customer's name, txtCustomer is the naming convention.

Text property: Used to Get or Set the text in the text box control.
To retrieve the text use variable = txtCustomer.Text, to set the text use txtCustomer.Text = 'Peter'

BackColor and ForeColor are used to set or Get the background and foreground color of the textbox control, respectively.

If you want the textbox control to bound to a data source, you can set the DataSource property of the textbox. You can set ODBC, OLEDB data source for the textbox. Set the DataMember property to the field in the database table. For example if you want to set the Customer tables, customer name property you can do it with datamember property. Use recordset's MoveNext, MovePrevious methods to navigate through record set.

PasswordChar property: PasswordChar is used for textbox for password input. The input character is replaced by password character defined by PasswordChar property. Usualy the asterisk (*) is used for password character. For security purpose the input character will be replaced by password character.

MaxLength Property: To define the maximum acceptable length of text in the textbox. For example you can set 20, to customer name textbox to restrict the number character in customer name to 20.

Locked Property: If set to True you can not edit the text in the textbox control.

Enabled Property: If set to false you can set focus on the control. Otherwise the textbox control will not receive focus and will not respond to user generated events.

Font Property: To set the Font family, font size and font style this property is used.

Multiline property: By default textbox control contain only one line. The text can not be wrapped to next line. To allow the textbox to receive carriage returns set the multiline property to true.

Visible Property: If set to false the textbox will be hidden during application run time. You can set true to show the control.

Methods: The SetFocus and Refresh are the few important events supported by the TextBox control.

TextBox events:

Change event: This event occurs when the text inside the textbox control changes. This is usually the keyboard keypress, keydown event.

GotFocus event: This event occurs when the textbox control Receives focus.

KeyDown event: Keydown occurs when the user press a key including control keys. KeyCode and Shift are the arguments in keydown event. The keycode contains the ASCII code of the key pressed. For example, if 'A' is pressed the keycode will contain 65, the ASCII equivalent for 'A'. The shift argument tells the state of the shift key. '0' means shift key not pressed. '1' means shift key was pressed.

KeyPress event: When a printable character is pressed the keypress event will fire. The only argument KeyAscii contains the ASCII code of the key pressed. To get the appropriate character us Chr(keyAscii) method. The non printable controls include, the CAPS key, Insert key, Delete Key, Home key, End key, Page up key, Page down key. These keys are not captured in keypress event. To capture these keys use the KeyDown event.

MouseDown, MouseMove, MouseUp events are fired when mouse button goes down, up.

Validate event: This event is fired when the textbox control is about to lose focus. The cancel property can be set to True to keep the focus. In other words you can validate the contents in the textbox and warn the user if the input is in wrong format or not in accordance with the business logic. For example you can validate it is valid number or not using IsNumberic function. If not numeric set Cancel to True and warn user with a message box pop up.

I think i have covered the important Properties, methods and events of the textbox control. I will write separate articles for specific usage of textbox control.

Monday, January 4, 2010

label control in VB 6.0

Label tutorial in Visual Basic

Label is one of the most used control in Visual Basic Designer. By the name implies label is used to display a descriptive text / message about the preceding control. For example there may be a text box control to receive customer Name. We put a label before the text box to intimate the user that he should type the customer name in the box.

The most common properties of label control is Caption property and name property. Label also supports database connectivity. You can connect a label control to a database table, and link a field from the table to display its contents. Another popular property is Visible. You can either set True or False to show or hide the control.

For example, you can add a Label to the top of a Form that provides instructions to the user on how to input data in the controls on the form. Label controls can be also used to display run time information on the status of an application. For example, you can add a Label control to a form to display the status of each file as a list of files is processed.

You can create a simple clock project to display and update current time. Just put a timer control on the form and set the timer interval to 1000 milliseconds. In the timer event set the lable's caption property to Time(). This will update the time each second. We will learn more about timer control in subsequent lessons.

Saturday, January 2, 2010

WebBrowser in VB 6.0

How to create a web browser in vb 6.0?

Visual Basic 6.0 does't have built-in support for internet and HTML web browsing. HTML browsing can be accomplished through web browser control, a Microsoft product. You can create a web browser application within minutes using the following step-be-step instructions. This tutorial is intended for beginners / novice in vb language.

Tutorial for creating web browser in visual basic 6.0

Step 1:

Create a new Standard Exe project in vb. Go to Project -> Components and select 'Microsfot Internet Controls'. This component contains the web browser control. Tick 'Microsoft Internet Controls' check box and click Ok. A new webbrowser control will be placed on the Toolbox.

Step 2:


Drag the web browser control from the toolbox on to the form, alternatively you can double click the control. A new instance of the control will be placed on the form. Give the control a name you wish. For example, MyBrowser. There are naming conventions for using built-in vb controls. But for third party controls there are no such conventions. Insert a textbox control on the form and give it the name 'txtAddress'. For textbox we use txt as prefix. Set the text property of the text box to 'www.google.com' so get get default web address to google.com. Add a label control and set it's name property to lblAddress and caption property to 'Address'. The 'lbl' is the naming convention used to prefix the label control. Add a command button control and give it the name 'cmdGo' or 'cmdBrowse'. Set its caption property to 'Go' or 'Browse'. We have all done with the design or GUI for our web browser project. Now, on to the step 3.

Step 3:

Now double click the command button. Private Sub cmdBrowse_Click() procedure will be added automatically by vb. Simple write the following code with in the sub procedure.

Private Sub cmdBrowse_Click()

MyBrowser.Navigate txtAddress.Text

End Sub

This is the only code required to open a web page on our new browser. The navigate method of the browser control with web address as its parameter will open the webpage on the specified URL (universal Resource Locator). This is the basic web browser with bare-bone web browsing option.

Setp 4:

We have finished our browser project. To test the project Run the project by pressing F5. Click the Browse button, the google.com home page will open!