Vous êtes sur la page 1sur 19

UNIT II

Command Buttons:Command buttonsthe plain buttons that you simply click and releaseare the most common type of buttons. These are the buttons you see everywhere in Visual Basic applications. They are usually just rounded, rectangular, gray buttons with a caption. Reacting To Command Button Clicks You respond to button clicks with the buttons Click event. To add a Click event handler, just double-click the button at design time, which adds a subroutine like this one: Private Sub Command1_Click() End Sub

Place the code you want to execute when the button is clicked in this subroutine: Example: Private Sub Command1_Click() MsgBox "You clicked the command button!" End Sub You can also add Event Handlers for various events such as SetFocus, LostFocus etc. Setting A Command Buttons Caption You use a buttons Caption property to set its caption. This property is available at both design time and runtime. After you add a button to a form, you set its caption by placing the appropriate text in the Caption property in the Properties window. You can also change the buttons caption at runtime, of course As Command1.Caption = "Click Me"

Setting A Command Buttons Background Color You can use the buttons BackColor property for this you have to set the buttons Style property to Graphical (which has a numeric value of 1) then with the help of backcolor property you can set the background color of the button at the design time. You can also set the buttons BackColor property at runtime, setting it to a value using the RGB() function, which takes three parameters (0 to 255) for the red, green, and blue color values you want to set. Here, we change the color of a graphical button to red: Command1.BackColor = RGB(255, 0, 0) Setting Command Button Fonts Selecting the Font item in the Properties window opens the Font dialog box Notice that there are number of options in the Font dialog box. You can use the following properties: FontBold FontItalic FontName FontSize FontStrikethru FontUnderline

CheckBoxes:Checkboxes are also familiar controls. You click a checkbox to select it and click it again to deselect it. When you select a checkbox, a checkmark appears in it, indicating that the box is indeed selected. Reacting To CheckBox Clicks You respond to button clicks with the buttons Click event. To add a Click event handler, just double-click the button at design time, which adds a subroutine like this one: Private Sub Command1_Click() End Sub

Place the code you want to execute when the button is clicked in this subroutine:

Example: Private Sub check1_Click() MsgBox "You clicked the Check Box!" End Sub You can also add Event Handlers for various events such as SetFocus, LostFocus etc. Setting A CheckBox Caption You use a CheckBoxs Caption property to set its caption. This property is available at both design time and runtime. After you add a button to a form, you set its caption by placing the appropriate text in the Caption property in the Properties window. You can also change the CheckBoxs caption at runtime, of course As check1.Caption = "Click Me"

Setting A checkboxs Background Color You can use the checkbox BackColor property for this you have to set the buttons Style property to Graphical (which has a numeric value of 1) then with the help of backcolor property you can set the background color of the button at the design time. You can also set the buttons BackColor property at runtime, setting it to a value using the RGB() function, which takes three parameters (0 to 255) for the red, green, and blue color values you want to set. Here, we change the color of a graphical button to red: check1.BackColor = RGB(255, 0, 0) Setting CheckBox Fonts Selecting the Font item in the Properties window opens the Font dialog box Notice that there are number of options in the Font dialog box. You can use the following properties: FontBold FontItalic FontName FontSize FontStrikethru FontUnderline

Getting A Checkboxs State Youve added all the checkboxes you need to your new program and youve connected those checkboxes to Click event handlers. But now theres a problemHow can you determine which one theyve checked? You can see if a checkbox is checked by examining its Value property . Here are the possible Value settings for checkboxes: 0 Unchecked 1 Checked 2 Grayed Heres an example; in this case, we will change a command buttons caption if a checkbox, Check1, is checked, but not otherwise: Private Sub Command1_Click() If Check1.Value = 1 Then Command1.Caption = "The check mark is checked" End If End Sub Setting A Checkboxs State You can set a checkboxs state by setting its Value property to one of the following: 0Unchecked 1Checked 2Grayed Heres an example; In this case, we check a checkbox, Check1, from code: Private Sub Command1_Click() Check1.Value = 1 End Sub

Option buttons
Option buttons, also called radio buttons, are like checkboxes in that you select and deselect them. However, they are round, whereas checkboxes are square, and you usually use option buttons together in groups. In fact, thats the functional difference between checkboxes and option buttons: checkboxes can work independently, but option buttons are intended to work in groups. When you select one option button in a group, the others are automatically deselected.

Reacting To Option Button Clicks You respond to option button clicks with the option buttons Click event. To add a Click event handler, just double-click the option button at design time, which adds a subroutine like this one: Private Sub option1_Click() End Sub

Place the code you want to execute when the button is clicked in this subroutine: Example: Private Sub option1_Click() MsgBox "You clicked the command button!" End Sub You can also add Event Handlers for various events such as SetFocus, LostFocus etc. Setting an option Buttons Caption You use a buttons Caption property to set its caption. This property is available at both design time and runtime. After you add a option button to a form, you set its caption by placing the appropriate text in the Caption property in the Properties window. You can also change the option buttons caption at runtime, of course As option1.Caption = "Click Me" Setting an option Buttons Background Color You can use the option buttons BackColor property for this you have to set the buttons Style property to Graphical (which has a numeric value of 1) then with the help of backcolor property you can set the background color of the button at the design time. You can also set the option buttons BackColor property at runtime, setting it to a value using the RGB() function, which takes three parameters (0 to 255) for the red, green, and blue color values you want to set. Here, we change the color of a graphical button to red: Command1.BackColor = RGB(255, 0, 0)

Setting option Button Fonts Selecting the Font item in the Properties window opens the Font dialog box Notice that there are number of options in the Font dialog box. You can use the following properties: FontBold FontItalic FontName FontSize FontStrikethru FontUnderline
Grouping Option Buttons Together When you add option buttons to a form, they are automatically coordinated so that only one option button can be selected at a time. If the user selects a new option button, all the other options buttons are automatically deselected. But there are times when thats not convenient. For example, you may have two sets of options buttons: days of the week and day of the month. You want the user to be able to select one option button in each list. How do you group option buttons together into different groups on the same form? You can use the frame control to group option buttons together (and, in fact, you can also use Picture Box controls). Just draw a frame for each group of option buttons you want on a form and add the option buttons to the frames (in the usual wayjust select the Option Button tool and draw the option buttons in the frames). Each frame of option buttons will act as its own group, and the user can select one option button in either group Getting An Option Buttons State You can check if an option button is selected or not with the Value property. Unlike checkboxes, which have three settings for the Value property (corresponding to checked, not checked, and grayed), option buttons Value property only has two settings: True if the button is selected, and False if not. Heres an example showing how to see whether or not an option button is selected. In this case, we display a message in a message box that indicates if an option button, Option1, is selected: Private Sub Command1_Click() If Option1.Value Then MsgBox "The option button is selected." Else MsgBox "The option button is not selected." End If End Sub

Setting An Option Buttons State

Besides examining an option buttons state, you can also set it using the Value property. The Value property can take two values: True or False. Heres an example. In this case, we just set an option button, Option1, to its selected state by setting its Value property to True: Private Sub Command1_Click() Option1.Value = True End Sub Disabling Commamd Button ,CheckBox , Option Button you can disable the button by setting its Enabled property to False when its inappropriate to use that button. When a button is disabled, it is inaccessible to the user (and it cant accept the focus). Disabling buttons in a form. You can also disable buttons at runtime, of course, like this: Private Sub Command1_Click() Command1.Enabled = False Option1.Enabled = False Check1.Enabled = False End Sub Showing And Hiding Commamd Button ,CheckBox , Option Button we can disable buttons using the Enabled property. However, its an inefficient use of space (and frustrating to the user) to display a lot of disabled buttons. If you have to disable a lot of buttons, you should hide them. To make a button disappear, just set its Visible property to False. To make it reappear, set the Visible property to True. You can set this property at either design time or runtime. Heres how to make a button disappear when you click it (and probably startle the user!): Private Sub Command1_Click() Command1.Visible = False option1.Visible = False check1.Visible = False End Sub

List Boxes
List boxes do just what their name implies: display a list of items. The user can make a selection from that list, and Visual Basic will inform our program whats going on. Because list boxes can use scroll bars if a list gets too long, these controls are very useful to present long lists of items in a way that doesnt take up too much space. Adding Items To A List Box You can add items to a list box at either design time or at runtime. At design time, you can use the List property, which is a very handy array of the items in the list box; and at runtime, you can use both the List property and the AddItem() method. Heres how you use the List property in code (keep in mind that you can get or set items in the list box with the List array): ListBox.List(index) [= string] How do you keep track of the total number of items in a list box? You use the ListCount property; that is, if you loop over the List array, youll use ListCount as the maximum value to loop to. Selecting the List property displays a drop-down list (which is appropriate considering youre filling a list box), and you can type item after item into the list box that way. At runtime, you can either use the indexed List property as detailed previously, or the AddItem() method this way: Private Sub Form_Load() List1.AddItem (Item 1) List1.AddItem (Item 2) List1.AddItem (Item 3) List1.AddItem (Item 4) End Sub Referring To Items In A List Box By Index When you add items to a list box, each item is given an index, and you can refer to the item in the list box using this index (for example, you can get the items text by using the List property: List(index)). The first item added to a list box gets the index 0, the next index 1, and so on When the user selects an item in a list box, you can get the selected items index with the list boxs ListIndex property. we can display the item number the user clicked with the ListIndex property, which holds the index of the currently selected item:

Private Sub List1_Click() MsgBox "You clicked item " & Str(List1.ListIndex) End Sub Responding To List Box Events

Click And DblClick


You use two main events with list boxes: Click and DblClick. You use the Click event just as you use the Click event in a button, with a Click event handler. Here, we display the item in the list box the user has clicked, using the ListIndex property (you can get the selected items text with List1.List(ListIndex) or with List1.Text): Private Sub List1_Click() MsgBox "You clicked item " & Str(List1.ListIndex) End Sub And displaying the selected item is the same for DblClickyou just add a DblClick handler with the code you want: Private Sub List1_DblClick() MsgBox "You clicked item " & Str(List1.ListIndex) End Sub Note, by the way, that a DblClick event also triggers the Click event, because to double-click an item, you must first click it.
Removing Items From A List Box You can remove items from a list box at design time simply by deleting them in the List property. At runtime, you use the RemoveItem() method. Item 0 has index 0 in the list box, Item 1 has index 1, and so on. To remove, say, Item 1 when the user clicks a command button, we can use RemoveItem and pass it the items Private Sub Command1_Click() List1.RemoveItem 1 End Sub

Clearing A List Box You can use the Clear method to clear a list box. Private Sub Command1_Click() List1.Clear End Sub

COMBO BOXES
Combo boxes are those controls that usually display a text box and a drop-down list. In fact, you might think there is only one kind of combo box, but there are really three types, and you select which type you want with the combo boxs Style property. The default type of combo box is probably what you think of when you think of combo boxes, because, as mentioned, it is made up of a text box and a drop-down list. Here are the settings for the combo box Style property: VbComboDropDown0; drop-down combo box. Includes a drop-down list and a text box. VbComboSimple1; simple combo box. Includes a text box and a list, which doesnt drop down VbComboDrop-DownList2; drop-down list. This style allows a selection only from the drop-down list Adding Items To A Combo Box A combo box is a combination of a text box and a list box, so at design time, you can change the text in the text box part by changing the Text property. You change the items in the list box part with the List property At runtime, you can add items to a combo box using the AddItem() method, which adds items to the list box part. You can also add items to the list box using the List property, which is an indexed array of items in the list box. If you want to set text in the text box, set the combo boxs Text property. Private Sub Form_Load() Combo1.AddItem ("Item 0") Combo1.AddItem ("Item 1") Combo1.AddItem ("Item 2") Combo1.AddItem ("Item 3") End Sub You can also add items to the list with the List property. Here we create a fifth item and give it a caption this way:

Private Sub Form_Load() Combo1.AddItem ("Item 0") Combo1.AddItem ("Item 1") Combo1.AddItem ("Item 2") Combo1.AddItem ("Item 3") Combo1.List(4) = "Item 4" End Sub Responding To Combo Box Selections Combo boxes are combinations of text boxes and list boxes, and that combination means that there are two sets of input events: Change events when the user types into the text box and Click or DblClick when the user uses the mouse.

Change Events
When the user changes the text in a combo box, a Change event occurs, You can read the new text in the text box with the Text property.

Private Sub Combo1_Change() MsgBox "New text is: " & Combo1.Text End Sub

Click Events
You can also get Click events when the user makes a selection in the list box using the mouse. You can determine which item the user clicked using the combos ListIndex property (which holds the index of the clicked item) or get that items text using the Text property Private Sub Combo1_Click() MsgBox "You clicked item " & Str(Combo1.ListIndex) End Sub Removing Items From A Combo Box you can remove items from combo boxes using the RemoveItem() method. You just pass the index of the item you want to remove from the combo boxs list to RemoveItem(). Private Sub Command1_Click() Combo1.RemoveItem 1 End Sub

Getting The Current Selection In A Combo Box When you make a selection in a combo box, that new selection appears in the combo boxs text box, so its easy to get the current selectionyou just use the combo boxs Text property. Private Sub Command1_Click() MsgBox "New text is: " & Combo1.Text End Sub

Clearing A Combo Box you can clear a whole combo box at once with the Clear() method. Private Sub Command1_Click() Combo1.Clear End Sub

Locking A Combo Box You can lock a combo box by setting its Locked property to True. When locked, the user cannot enter text in the combos text box and cannot make selections from the combos list (although if the list is drop-down, it will still open).

TEXT BOXES
Every Windows user is familiar with text boxes. Theyre exactly what their name implies: box-like controls in which you can enter text. Text boxes can be multiline, have scroll bars, be read-only, and have many other attributes Creating Multiline, Word-Wrap Text Boxes You can do that by setting the text boxs MultiLine property to True, Aligning Text In Text Boxes text boxes have an Alignment property, (there are three possibilities: 0 for leftjustified, 1 for right-justified, and 2 for centered. You need to set the text boxes MultiLine property to True before text alignment will work

Locking A Text Box

You use the Locked property to make a text box read-only. Setting this property to True means that the user cannot enter text into the text box except under your programs control, like this: Private Sub Command1_Click() Text1.Text = "This box is locked." End Sub

Disabling A Text Box


You can also disable a text box by setting its Enabled property to False. Accessing Text In A Text Box you use the Text property like this: Private Sub Command1_Click() Text1.Text = "Hello from Visual Basic" End Sub Selecting And Replacing Text In A Text Box To work with part of the text in a text box, you select the text you want using three properties: SelLengthReturns or sets the number of characters selected. SelStartReturns or sets the starting point of selected text. If no text is selected, SelStart indicates the position of the insertion point. SelTextReturns or sets the string containing the currently selected text. If no characters are selected, SelText consists of a zero-length string (). Note the use of Len() to get the length of the text currently in the text box: Private Sub Command1_Click() Text1.SelStart = 0 Text1.SelLength = Len(Text1.Text) Text1.SelText = "Welcome to Visual Basic" End Sub Thats how it works when you want to select some text: you specify the beginning of the selected text in SelStart, the end in SelLength, and refer to the text with the SelText property.

IMAGE CONTROL
Image Controls You use image controls to do just what the name implies: display images. This control is a very simple one that doesnt take up many program resources: its just there to display (and stretch, if you wish) images. If thats all you want to do, use an image control. You load a picture into an image controls Picture property (either at design time or using LoadPicture() at runtime). Image controls are very accommodatingthey resize themselves automatically to fit the image youre placing in them. On the other hand, if you dont want the image control to change size, set its Stretch property to True. Doing so means that the image, not the control, will be resized when loaded to fit the control. Another advantage of the image control over the picture box is that it repaints itself faster than picture boxes. Image boxes cant do a lot of things that picture boxes can do, however, such as act as containers for other controls.

Picture Boxes Picture boxes are more complete controls than image controls. Just as the rich text control provides a sort of word-processor-in-a-control, so the picture box does for graphics in Visual Basic. You can load images into a picture box, save images to disk, draw with some rudimentary graphics methods, print images, work pixel-by-pixel, set an images scale, and more. As with image controls, you load pictures into a picture boxs Picture property, and you can do that at design time or runtime (at runtime you use the LoadPicture() method). When you load an image into a picture box, the picture box does not resize itself by default to fit that image as the image control doesbut it will if you set its AutoSize property to True. Load the image you want to display into the picture box using its Picture property. Click that property in the Properties window and click the button with an ellipsis (...) in it to open the Load Picture dialog box. At runtime, you can load a picture using LoadPicture() like this: Private Sub Command1_Click() Picture1.Picture = LoadPicture _ ("c:\vbbb\picturesandimages\image.bmp") End Sub

Setting Or Getting The Picture In A Picture Box A picture box is very versatile and can display images from bitmap (.bmp), icon (.ico), metafile (.wmf), JPEG (.jpg), or GIF (.gif) filesjust load the files name into the Picture property.

At design time, click that property in the Properties window and click the button with an ellipsis (...) in it to open the Load Picture dialog box. Specify the file you want to load into the picture box, and click on OK. At runtime, you can use LoadPicture() to load in a picture like this, where we load in an image when the user clicks a command button: Private Sub Command1_Click() Picture1.Picture = LoadPicture("c:\vbbb\picturesandimages\image.bmp") End Sub
If you want to get the picture in a picture box, you also use the Picture property. For example, here we copy the picture from Picture1 to Picture2 when the user clicks a command button: Private Sub Command1_Click() Picture2.Picture = Picture1.Picture End Sub Besides the Picture property, picture boxes also have an Image property. The Image property is actually the handle to the images bitmap in the picture box and as such is very useful when working with Windows calls directly. You can also assign images from an Image property to a Picture property like this: Private Sub Command1_Click() Picture2.Picture = Picture1.Image End Sub

The Label Control You use label controls to display text that you dont want the user to change directly. As their name implies, you can use these controls to display text that labels other parts of the form that dont have their own captions. For example, you might label a picture box something like Current image. Despite their name, label controls are not static. You can change the text in a label at runtime by setting its Caption property, and in fact thats often a very useful thing to

do if you dont want the user to change that text. The label control may be far from what you think of as a standard label, because the text in the label will change, labels can indeed display any kind of textyou can even format, word wrap, or size a label to fit its text. All in all, labels are one of the most useful Visual Basic controls. They can even have Click events. The Label Control tool appears in the toolbox as the second tool down on the left.

Formatting Text In Labels When you add labels to a form, you can make the label match the texts size or wrap as needed by setting these label control properties: AutoSize makes the label size itself to fit the text. WordWrap enables word wrap if lines of text are too long. In addition, you can format the text in a label with these properties, making the text appear in any font or font size, or with attributes like bold or underline: FontBold FontItalic FontName FontStrikeThru FontUnderline Keep in mind that you can use labels as a read-only text box, so formatting the text can be a very useful thing to do.

Handling Label Control Events labels have events like Click and DblClick. Using these events can be a good thing if youre using a label control as more than just a labelfor example, to reset a setting of some kind. event handle for the labels DblClick event: Private Sub Display_DblClick() End Sub Aligning Text In Labels As with text boxes, you can align text in labels. To do that, you just set the labels

Alignment property at design time or runtime. Here are the possible values for the Alignment property: VbLeftJustify0 (the default); text is left-aligned VbRightJustify1; text is right-aligned VbCenter2; text is centered

LINE CONTROL
The line control does just as its name implies: it draws a line. You can draw lines at design time simply as you would any other controljust click the Line Control tool in the toolbox, press the mouse button at one end of the line you want, and drag the mouse to the other end. The line controls primary properties are X1, X2, Y1, and Y2, and those values form the coordinates of the line segment: (X1, Y1) and (X2, Y2). You can even change those values at runtime to move or resize the line (line controls do not have a Move method). You can also draw lines with this control in forms, picture boxes, and in frames. In fact, lines drawn with the line control stay visible even if its containers AutoRedraw property is set to False (unless its Visible property is set to False). As an example, weve drawn a few lines in the form in Figure 14.13 using the line control
Drawing Thicker, Dotted, And Dashed Lines Using the line control, you can select a line style with the BorderStyle property. Here are the possible values for the line controls BorderStyle property: vbTransparent0; transparent vbBSSolid1 (the default); solid vbBSDash2; dash vbBSDot3; dot vbBSDashDot4; dash-dot vbBSDashDotDot5; dash-dot-dot vbBSInsideSolid6; inside solid To set a lines width, you use the BorderWidth property (the default value is 1).

Data Control
Adding A Data Control To A Program The data control is the only intrinsic database controlits already in the toolbox. This controls tool appears as the tenth tool down on the right in the toolbox. Stretch the data control as you want it. When you stretch the control beyond its original size, youll see a space for text in the center of the control; set the controls Caption property to the name of the database. Opening A Database With The Data Control 1. Set the data controls DatabaseName property to the path and name of the Access/Jet database file you want to open. 2. Select the table you want to work with the data controls RecordSource property. With the above two steps setting the properties in the properties window, we open a database. Connecting A Data Control To A Bound Control Previously, we connected a database to a data control, to see that data well use a databound controla text box. To connect a text box to a data control:1. Set the text boxs DataSource property to the name of the data control for example Data1. 2. Place the fields name(name of the column in the database) in the text boxs DataField property. Properties used for data control are:1. Caption used to set caption of the data control. 2. DatabaseName name of the Access/Jet database file you want to open 3. RecordSource name of the Access/Jet database file you want to select Properties used for data control are:DataSource DataField
-

Select data control as datasource. name of the field used to show in text box

The Data Controls Methods The built in functionality of data Control, can be accessed through applications code with the Data controls methods. The simplest methods are the navigation methods, which correspond to the action of the four buttons on the control, they are as follows:-

MoveFirst repositions the control to the first record. MoveLast repositions the control to the last record. MovePrevious repositions the control to the previous record. MoveNext repositions the control to the last record.

However implementing these methods care should be taken (1) what happens when the data control is positioned at the first or last record (2) what happen when previous button is clicked when positioned at first record (3) what happen when next button is clicked when positioned at last record. The Find Methods In addition to the navigation methods, the data control provides four methods for finding records in recordset. The following methods locate records: FindFirst finds the first record that meets the specified criteria. FindLast finds the last record meeting specified criteria. FindNext finds the Next record meeting specified criteria. FindPrevious finds the Previous record meeting specified criteria.

These methods can locate any record in the recordset, based on the user specified criteria Ex:Data1.recordset.FindFirst

Vous aimerez peut-être aussi