Professional Documents
Culture Documents
Typed Notes Chapters 2nd 4th and 6th Notes
Typed Notes Chapters 2nd 4th and 6th Notes
Typed Notes Chapters 2nd 4th and 6th Notes
To display the shortcut next to the menu item's caption at run time, you set the ShowShortcut
property to True (it's True by default).
For example, in the Menus example, I've given the Exit item in the File menu a shortcut of
Ctrl+X, as you can see next to its caption. When the user presses Ctrl+X, this item is activated.
At design time, just select a shortcut key combination from the list that appears when you select
the Shortcut property of any menu item in the properties window.
At Design Time,
At run time,
Public Class MenuExamples
Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MenuItem1ToolStripMenuItem.Click
MenuItem1ToolStripMenuItem.ShowShortcutKeys = True
MenuItem1ToolStripMenuItem.ShortcutKeyDisplayString = "Ctrl D"
End Sub
End Class
1 VB.NET Notes
2 VB.NET Notes
Adding Checkmarks to Menu Items
At Design Time,
If the Checked property is True, the checkmark is displayed, False means it's hidden.
The checkmark in front of the Spell Checking item toggles on and off when you select that item,
because the code flip the logical sense of the Checked property with the Not operator:
At Run Time,
OR
3 VB.NET Notes
Creating Menu Access Keys
Access keys make it possible to select menu items from the keyboard using the Alt key. For
example, if you make the "F" in the File menu's caption an access key and the "x" in the Exit
menu item an access key, the user can select the Exit item by typing Alt+F to open the File
menu, then Alt+X to select the Exit item.
To give an item an access key, you precede the access key in its caption with an ampersand (&).
In this example, that means using the captions "&File" and "E&xit". Access keys are underlined
in menu captions.
Click Event
For example, you can add code to display a message box when a menu item is selected, like this:
4 VB.NET Notes
Using the Popup Event
The MenuItem Popup event occurs when a menu item is about to be displayed, and you can
execute code to configure the item in this event's handler. For example, you might have an item
that lets the user connect to the Internet, and you might want to set the caption to "Connect" if
they are presently disconnected, and "Disconnect" if they're connected. Here's an example that
uses this event to display a message box before the corresponding menu item is displayed:
ToolStrip or Toolbars
• Toolbars provide a quick way to select menu items.
• Toolbar contains buttons, that can be accessed quickly.
• For example, to save the file you're currently working on, you only need to click the diskette button
in the standard toolbar.
• In Windows the toolbars are full of buttons that appear under menu bars.
• The ToolStrip used to create easily customized, commonly employed toolbars that
support advanced user interface and layout features
5 VB.NET Notes
ToolStrip Class Hierarchy
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ScrollableControl
System.Windows.Forms.ToolStrip
Properties of ToolStrip
Property Means
AutoSize Gets/sets whether the toolbar can change its size automatically.
Buttons Gets the collection of buttons in the toolbar.
Divider Gets/sets whether the toolbar shows a divider.
DropDownArrows Gets/sets if drop-down buttons display down arrows.
ShowToolTips Gets/sets if the toolbar displays a tool tip for each button.
TextAlign Gets/sets the alignment of text in the toolbar button controls.
Wrappable Gets/sets if toolbar buttons wrap to the next line as needed.
Events of ToolStrip
Event Means
ButtonClick Occurs when a button in the toolbar is clicked.
ButtonDropDown Occurs when a drop-down button or its down arrow is clicked.
6 VB.NET Notes
Creating ToolStrip
At design time, select ToolStrip component in the toolbox and add to the form.
7 VB.NET Notes
StatusStrip Control
It is used to display some text that represents the status of the application and user actions.
The Windows Forms StatusStrip control is used on forms as an area, usually displayed at
the bottom of a window, in which an application can display various kinds of status information.
8 VB.NET Notes
DoubleClick Occurs when the form is double-clicked.
Load Occurs before a form is displayed for the first time.
Closed Occurs when the form is closed.
KeyUp Occurs when a key is released while the form has focus.
KeyDown Occurs when a key is pressed down while the form has focus.
KeyPress Occurs when a key is pressed while the form has focus.
MouseUp Occurs when the mouse pointer is over the form and a mouse button is released.
MouseDown Occurs when the mouse pointer is over the form and a mouse button is pressed.
MouseMove Occurs when the mouse pointer is moved over the form.
9 VB.NET Notes
The Built-in Dialog Boxes
The following are the number of built-in dialog boxes in Visual Basic:
You use the ShowDialog method to display the dialog at run time and can check its return value
such as DialogResult.OK or DialogResult.Cancel to see which button the user has clicked.
10 VB.NET Notes
• The ReadOnlyChecked property indicates whether the read-only checkbox is selected.
• The Filter property sets the current file name filter string, which determines the choices that
appear in the "Files of type" box in the dialog box.
• The name and path the user selected is stored in the FileName property of the
OpenFileDialog object.
• The OpenFile method to open the selected file directly.
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.CommonDialog
System.Windows.Forms.FileDialog
System.Windows.Forms.OpenFileDialog
Properties of OpenFileDialog
Property Means
FileName Gets/sets the file name selected in the file dialog box.
FileNames Gets the file names of all selected files.
InitialDirectory Gets/sets the initial directory used in the file dialog box.
Multiselect Gets/sets whether the dialog box allows multiple file selections.
Title Gets/sets the file dialog box title.
AddExtension Gets/sets if the dialog box adds an extension to file names if the user doesn't
supply the extension.
CheckFileExists Gets/sets if the dialog box displays a warning if the user specifies a
nonexistent file.
CheckPathExists Gets/sets whether the dialog box displays a warning if the user gives a path
that does not exist.
DefaultExt Gets/sets the default file extension.
Methods of OpenFileDialog
Method Means
ShowDialog Shows the dialog box.
11 VB.NET Notes
Method Means
OpenFile Opens the file selected by the user, with read-only permission. The file is
specified by the FileName property.
Reset Resets all options to their default values.
Event Means
FileOk Occurs when the user clicks the Open or Save button.
HelpRequest Occurs when the user clicks the Help button.
This example lets the user open an image in a picture box. If the user did not click the Cancel
button, the code loads the corresponding image into the picture box in this example this way:
Ex:
Ex:
12 VB.NET Notes
InitialDirectory property
Another useful property to know about is the InitialDirectory property, which lets you set the
directory that the Open File dialog box first shows; here's an example:
openFileDialog1.InitialDirectory = "c:\datafiles"
• The ShowDialog method is used to display the dialog box at run time.
• The FileName property is used to get the file the user selected.
• The OpenFile method is used to open a file in read-write mode.
Property Means
FileName Gets/sets the file name selected in the file dialog box.
FileNames Gets the file names of all selected files.
InitialDirectory Gets/sets the initial directory used in the file dialog box.
Multiselect Gets/sets whether the dialog box allows multiple file selections.
Title Gets/sets the file dialog box title.
AddExtension Gets/sets if the dialog box adds an extension to file names if the user doesn't
supply the extension.
CheckFileExists Gets/sets if the dialog box displays a warning if the user specifies a
nonexistent file.
CheckPathExists Gets/sets whether the dialog box displays a warning if the user gives a path
that does not exist.
DefaultExt Gets/sets the default file extension.
Methods of SaveFileDialog
Method Means
ShowDialog Shows the dialog box.
OpenFile Opens the file selected by the user, with read-only permission. The file is
specified by the FileName property.
Reset Resets all options to their default values.
Event Means
FileOk Occurs when the user clicks the Open or Save button.
HelpRequest Occurs when the user clicks the Help button.
For example, display the filename that the user selected in a message box:
14 VB.NET Notes
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog <> DialogResult.Cancel Then
MsgBox("You chose " & SaveFileDialog1.FileName)
End If
End Sub
Imports System.Windows.Forms
Public Class SaveDialogEx
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
SaveFileDialog1.InitialDirectory = "F:\opendialog"
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName & ".txt", "" &
TextBox1.Text, True)
End If
End Sub
End Class
Font Dialogs
• Font dialogs let the user select a font size, face, color, and so on.
• The FontDialog class displays a dialog box that lets the user select a font.
• It returns a Font object in the Font property, and a Color object in the Color property.
• Font dialogs are supported by the FontDialog class.
15 VB.NET Notes
What's handy about these dialogs, besides the fact that they're the same as those used by
Windows, is that they return Font and Color objects directly (using the properties of the same
name), ready for installation in controls that can use them, like rich text boxes. This saves you
the trouble of creating and configuring these objects from scratch.
16 VB.NET Notes
To display the font dialog box, call the ShowDialog method. This dialog shows list boxes for
Font, Style, and Size, checkboxes for effects like Strikeout and Underline, a drop-down list for
Script (Script refers to different character scripts that are available for a given font—for
example, Hebrew), and a sample of how the font will appear. You can recover these settings
using properties of the same names of the Font object returned by the Font property.
Method Means
ShowDialog Shows the dialog.
Reset Resets all dialog options to default values.
Imports System.Windows.Forms
Imports System.Drawing
Public Class FontDialogEx
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
If FontDialog1.ShowDialog <> DialogResult.Cancel Then
TextBox1.Font = FontDialog1.Font
End If
End Sub
End Class
Output:
18 VB.NET Notes
Color Dialogs
• Color dialogs are used to select a color in an easy way.
• The principal property you use of these dialogs is the Color property, which returns a Color
object, ready for use.
• You can see a color dialog box at work in Figure 9.6.
In Figure 9.6, I've opened the color dialog fully (by clicking Define Custom Colors) to let the
user define their own colors with color values and hue, saturation, and luminosity. If you set the
AllowFullOpen property to False, on the other hand, the Define Custom Colors button is
disabled and the user can select colors only from the predefined colors in the palette. Note also
19 VB.NET Notes
that if you set the SolidColorOnly property to True, the user can select only solid (not dithered)
colors.
Properties of ColorDialog
Property Means
Color Gets/sets the color selected by the user.
SolidColorOnly Gets/sets whether the dialog box will restrict users to selecting solid colors
only.
CustomColors Gets/sets the set of custom colors shown in the dialog box.
AllowFullOpen Gets/sets whether the user can use the dialog box to define custom colors.
AnyColor Gets/sets whether the dialog box displays all available colors in the set of
basic colors.
methods of ColorDialog
Method Means
ShowDialog Shows the dialog.
Reset Resets all dialog options to their default
values.
Events of ColorDialog
Event Means
HelpRequest Occurs when the user clicks the Help button.
20 VB.NET Notes
Creating Color Dialogs
The example lets the user use a Color dialog to set the background color of a label control. In
code, all you have to do is to assign the Color object returned by the dialog box's Color property
to the label's BackColor property of the label's text "Change my color!":
The Color dialog that this example displays appears in Figure 9.6. You can use it to set the new
background color of the label, as you see in Figure 9.20. You can't see it in the black-and-white
figure, but I've set the background color to an appealing aqua blue there.
Print Dialogs
21 VB.NET Notes
Print dialogs let the user print documents, and these dialogs are supported with the PrintDialog
class.
Before displaying a Print dialog, you set the Document property of a PrintDialog object to a
PrintDocument object.
The PrinterSettings property to a PrinterSettings object of the kind set by Page Setup dialogs.
When the dialog is closed, you can print the document by assigning the PrintDialog object's
PrinterSettings property (which returns a PrinterSettings object as configured by the user,
indicating the number of copies to print, the printer to use, and so on) to the PrinterSettings
property of the PrintDocument object and use the PrintDocument object's Print method to
actually print the document. Here's how that might look in code:
You can see a Print dialog in Figure 9.7—this one comes from the Printing example on the CD-
ROM.
22 VB.NET Notes
PrintDialog Class Hierarchy
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.CommonDialog
System.Windows.Forms.PrintDialog
Properties of PrintDialog
Property Means
Document Gets/sets the PrintDocument used to obtain PrinterSettings.
AllowSelection Gets/sets whether the Selection radio button is enabled.
AllowSomePages Gets/sets whether the From... To... Page radio button is enabled.
PrinterSettings Gets/sets the PrinterSettings dialog box to modify.
ShowHelp Gets/sets whether the Help button is displayed.
ShowNetwork Gets/sets whether the Network button is displayed.
Methods of PrintDialog
Method Means
ShowDialog Shows the dialog.
Reset Resets all dialog options.
Events of PrintDialog
Event Means
HelpRequest Occurs when the user clicks the Help button.
23 VB.NET Notes
Chapter 2: Elements of Visual Basic
2 Marks Questions
1. What is a property?
Property is a named attribute of an object.
Properties define object characteristics such as size, color or the state of an object, such as
enabled or disabled.
Properties can be set at design time by using the Properties window or at run
time by using statements in the program code.
Where
For example,
TextBox1.Text = "Hello"
2. What is a method?
A method is a procedure created as a member of a class and they cause an
object to do something.
Methods are used to access or manipulate the characteristics of an object or a
variable.
For example, the MessageBox control has a method named Show, which is
called in the code snippet below −
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class
24 VB.NET Notes
3. What is an event? OR What is an event? Give an example.
• An event is a signal that informs an application that something important
has occurred.
• For example, when a user clicks a control on a form, the form can raise
a Click event and call a procedure that handles the event.
• There are various types of events associated with a Form like click, double
click, close, load, resize, etc.
4. Explain any two events of the form & Explain any two properties of form.
Properties
Table 4.1: Windows forms public object properties.
Property Description
Name Gets or sets the name of the form.
Text Gets or sets the text associated with this form.
BackColor Gets or sets the background color for this form.
ForeColor Gets or sets the foreground color of the form.
BackgroundImage Gets or sets the background image in the form.
Height Gets or sets the height of the form.
Width Gets or sets the width of the form.
Size Gets or sets the size of the form.
Visible Gets or sets a value indicating if the form is visible.
Enabled Gets or sets a value indicating if the form is enabled.
AcceptButton Gets or sets the button on the form that is pressed when the user uses the
Enter key.
CancelButton Indicates the button control that is pressed when the user presses the ESC
key.
FormBorderStyle Gets or sets the border style of the form.
Icon Gets or sets the icon for the form.
AutoScroll Indicates if the form implements autoscrolling.
DialogResult Gets or sets the dialog result for the form.
MaximizeBox Gets or sets a value indicating if the maximize button is displayed in the
caption bar of the form.
MinimizeBox Gets or sets a value indicating if the minimize button is displayed in the
caption bar of the form.
25 VB.NET Notes
Table 4.1: Windows forms public object properties.
Property Description
MaximumSize Returns the maximum size the form can be resized to.
MinimumSize Gets the minimum size the form can be resized to.
Events
Events let you know that something's happened with a form; for example, when you click a
form, a Click event occurs, and when the form is closed, a Closed event occurs.
26 VB.NET Notes
Table: Windows forms public object events
Event Description
MouseHover Occurs when the mouse pointer hovers over the form.
MouseLeave Occurs when the mouse pointer leaves the form.
MouseWheel Occurs when the mouse wheel moves while the form has focus.
CursorChanged Occurs when the cursor property value has changed.
By default TextBox is a single line entry, because multiline property is set by default false.
If the multiline property of TextBox is set to true, TextBox allow the user to enter multiline.
27 VB.NET Notes
public properties of Button objects.
Property Means
AutoSize Sets/gets a value specifying if the height of the control automatically adjusts
when the font in the control is changed.
28 VB.NET Notes
A List box is simply a list of items, while a Combo box is a combination of a List box and an
Edit box.
A List box allows the user to choose multiple selections from the list at one time, while a
Combo box allows only a single selection.
A Combo box allows the user to edit the selected value while a List box only allows the user
to choose from the given list.
The Windows forms combo box control is used to display data in a drop-down combo box.
• The top part is a text box that allows the user to type in all or part of a list item.
• The other part is a list box that displays a list of items from which the user can select one
or more.
Radio Buttons:
• A radio button is one of a group of controls representing mutually-exclusive choices.
29 VB.NET Notes
• A radio button is typically represented as a round control to distinguish from the square
checkbox control.
You can get the selected item's index with the list box's SelectedIndex property.
You also can get the selected item's corresponding object with the SelectedItem property.
30 VB.NET Notes
12.Write the class hierarchy of scroll bars.
Hierarchy:
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ScrollBar
System.Windows.Forms.HScrollBar
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ScrollBar
System.Windows.Forms.VScrollBar
• Tool tips are small windows that appear with explanatory text when you let the mouse rest on
a control or window.
• To give quick help when the mouse rests on an item, tool tips are used.
5 Marks Questions
1. Write and explain textbox with methods, properties and events. OR
Explain textbox with properties and events. Give one example for
implementing TextBox.
• Windows forms text boxes are used to get input from the user or to display text.
• The TextBox control is generally used for editable text, although it can also be made read-only.
• Text boxes can be multiline, have scroll bars, be read-only, and have many other properties.
31 VB.NET Notes
• The TextBox class is derived from the TextBoxBase class, which is based on Control:
Class Hierarchy:
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.TextBoxBase
System.Windows.Forms.TextBox
If you set the MultiLine property to True to make the control accept multiple lines of text.
The Text property can be set at design time with the Properties window, at run time in code, or by user
input at run time.
The current contents of a text box can be retrieved at run time by reading the Text property.
Ex:-
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = "Hello from Visual Basic"
End Sub
You can limit the amount of text entered into a TextBox control by setting the MaxLength property to a
specific number of characters.
TextBox controls also can be used to accept passwords if you use the PasswordChar property to mask
characters.
32 VB.NET Notes
public properties of TextBox objects.
Property Means
ScrollBars Sets/gets what scroll bars should appear in a multiline text box.
MaxLength Sets/gets the maximum number of characters the user can type into the text
box.
ReadOnly Sets/gets a value specifying if text in the text box is read-only.
SelectedText Sets/gets a value specifying the currently selected text in the control.
SelectionStart Sets/gets the starting point of text selected in the text box.
AutoSize Sets/gets a value specifying if the height of the control automatically adjusts
when the font in the control is changed.
BorderStyle Sets/gets the border type of the text box control.
33 VB.NET Notes
Events of TextBox objects
public events of TextBox objects.
Event Means
Click Occurs when the text box is clicked.
AutoSizeChanged Occurs when the value of the AutoSize property is changed.
ReadOnlyChanged Occurs when the value of the ReadOnly property is changed.
Event Means
Click Occurs when the form is clicked.
DoubleClick Occurs when the form is double-clicked.
Load Occurs before a form is displayed for the first time.
Closed Occurs when the form is closed.
KeyUp Occurs when a key is released while the form has focus.
KeyDown Occurs when a key is pressed down while the form has focus.
KeyPress Occurs when a key is pressed while the form has focus.
MouseUp Occurs when the mouse pointer is over the form and a mouse button is released.
MouseDown Occurs when the mouse pointer is over the form and a mouse button is pressed.
MouseMove Occurs when the mouse pointer is moved over the form.
Deactivate Occurs when the form loses focus and is not the active form.
34 VB.NET Notes
Accessing Text in a Text Box
Use the Text property to access text in the Text Box.
Ex:-
When the user clicks the command button Button1, the text "Hello from Visual Basic" appears in the
text box.
Class Hierarchy:
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.Label
35 VB.NET Notes
• The caption for a label is stored in the Text property.
• The TextAlign property allows you to set the alignment of the text within the label.
• You can set up mnemonic characters for them with the UseMnemonic property; just
specify a mnemonic character in their caption by preceding it with a & character.
• In that case, when the user presses Alt and the mnemonic character, the focus goes to
the control.
• It can support images in labels with the Image property, or the Image and ImageList
properties together.
UseMnemonic Sets/gets a value specifying if the control treats an ampersand character (&) in
the control's Text property to be an access key character.
Image Sets/gets the image that is displayed on a Label.
ImageAlign Sets/gets the alignment of an image that is displayed in the control.
AutoSize Sets/gets a value specifying if the control should be automatically resized to
display all its contents.
36 VB.NET Notes
Event Means
Click Occurs when the form is clicked.
DoubleClick Occurs when the form is double-clicked.
Load Occurs before a form is displayed for the first time.
Closed Occurs when the form is closed.
KeyUp Occurs when a key is released while the form has focus.
KeyDown Occurs when a key is pressed down while the form has focus.
KeyPress Occurs when a key is pressed while the form has focus.
MouseUp Occurs when the mouse pointer is over the form and a mouse button is released.
MouseDown Occurs when the mouse pointer is over the form and a mouse button is pressed.
MouseMove Occurs when the mouse pointer is moved over the form.
For example, you might want to display the result of a calculation in a label instead of a text box,
so the user can't edit that result.
Ex:
Lable1.Text=Val(TextBox1.Text)+Val(TextBox2.Text)
An example using the DoubleClick event to change the text in the label when the user double-
clicks it:
37 VB.NET Notes
3. Explain with example the Button control with properties and events.
• Buttons are used for creating and handling an event in your code.
• Buttons are the plain controls that you simply click and release
• The buttons rounded rectangular, gray buttons with a Text on it.
• Every Visual Basic programmer is familiar with the button Click event.
• Buttons can be clicked with the mouse or with the Enter key if the button has the focus.
The Button class is derived from the ButtonBase class as shown in the below class hierarchy for
Button:
Class Hierarchy:
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ButtonBase
System.Windows.Forms.Button
38 VB.NET Notes
Properties of Button objects
public properties of Button objects.
Property Means
TextAlign Gets/sets the alignment of the text in the button.
Image Gets/sets an image displayed in a button.
ImageList Gets/sets the ImageList that contains the images displayed in a button.
ImageAlign Gets/sets the alignment of the image in a button.
FlatStyle Gets/sets a flat style appearance.
DialogResult Gets/sets the value returned to the parent form when the button is clicked. Often
used when you're creating dialog boxes.
ImageIndex Gets/sets the image list index value of the image displayed in the button.
AutoSize Sets/gets a value specifying if the height of the control automatically adjusts
when the font in the control is changed.
39 VB.NET Notes
public events of Button objects.
Click Occurs when the form is clicked.
DoubleClick Occurs when the form is double-clicked.
KeyUp Occurs when a key is released while the form has focus.
KeyDown Occurs when a key is pressed down while the form has focus.
KeyPress Occurs when a key is pressed while the form has focus.
MouseUp Occurs when the mouse pointer is over the form and a mouse button is
released.
MouseDown Occurs when the mouse pointer is over the form and a mouse button is
pressed.
MouseMove Occurs when the mouse pointer is moved over the form.
You also can set the button's Background property at run time:-
You can also set the foreground color of a button. Much like the BackColor property, you can
set a button's ForeColor property at design time, or at run time, like this:
40 VB.NET Notes
End Sub
Ex:
You can use the Appearance property to specify if the checkbox appears as a typical checkbox
or as a button.
Also, the ThreeState property determines whether the control supports two or three states.
For standard checkboxes, you use the Checked property to get or set the value of a checkbox
control, but for three-state checkboxes, which support an "indeterminate" state, you use the
CheckState property.
The indeterminate state is sort of a middle state between checked and unchecked.
41 VB.NET Notes
You use the CheckState property to get or set the value of the three-state checkbox. The three
states are:
If you've set the checkbox's ThreeState property to True, you can set its CheckState property
to CheckState.Indeterminate at design time or run time to set the checkbox to the
indeterminate state:
Radio buttons, also called option buttons, are similar to checkboxes—the user can select and
deselect them.
42 VB.NET Notes
2. Radio buttons are work in groups whereas Checkboxes can work independently
When you select one radio button in a group, the others are automatically deselected.
You can see radio buttons at work in the below figure and in the RadioButtons example.
Like checkboxes, you use the Checked property to get or set the state of a radio button.
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ButtonBase
System.Windows.Forms.RadioButton
43 VB.NET Notes
Table: public properties of RadioButton objects.
Property Means
Appearance Gets/sets the value that determines the appearance of the radio button.
Checked Gets/sets a value indicating whether the radio button is checked.
Image Gets/sets the image that is displayed in a radio button.
ImageAlign Gets/sets the alignment of the image in a radio button.
ImageIndex Gets/sets the image list index value of the image displayed in a radio button.
ImageList Gets/sets the ImageList that contains the image displayed in a radio button.
TextAlign Gets/sets the alignment of the text in a radio button.
Checkbox
• The CheckBox control allows the user to select or deselect it options.
• When the user click a checkbox, a check mark appears in it, indicating that the box is
selected, it has the value true.
• When it is cleared, indicating that the box is deselected, it holds the value False.
Ex:
You can use the Appearance property to specify if the checkbox appears as a typical checkbox
or as a button.
44 VB.NET Notes
Also, the ThreeState property determines whether the control supports two or three states.
For standard checkboxes, you use the Checked property to get or set the value of a checkbox
control, but for three-state checkboxes, which support an "indeterminate" state, you use the
CheckState property.
The indeterminate state is sort of a middle state between checked and unchecked.
You use the CheckState property to get or set the value of the three-state checkbox. The three
states are:
45 VB.NET Notes
If you've set the checkbox's ThreeState property to True, you can set its CheckState property
to CheckState.Indeterminate at design time or run time to set the checkbox to the
indeterminate state:
RadioButton
Radio buttons, also called option buttons, are similar to checkboxes—the user can select and
deselect them.
When you select one radio button in a group, the others are automatically deselected.
You can see radio buttons at work in the below figure and in the RadioButtons example.
Like checkboxes, you use the Checked property to get or set the state of a radio button.
46 VB.NET Notes
Also, a radio button's appearance may be altered to appear as a toggle-style button or as a
standard radio button by setting the Appearance property.
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ButtonBase
System.Windows.Forms.RadioButton
Property Means
Appearance Gets/sets the value that determines the appearance of the radio button.
Checked Gets/sets a value indicating whether the radio button is checked.
Image Gets/sets the image that is displayed in a radio button.
ImageAlign Gets/sets the alignment of the image in a radio button.
ImageIndex Gets/sets the image list index value of the image displayed in a radio button.
ImageList Gets/sets the ImageList that contains the image displayed in a radio button.
TextAlign Gets/sets the alignment of the text in a radio button.
Radio Buttons:
• A radio button is one of a group of controls representing mutually-exclusive choices.
47 VB.NET Notes
• A radio button is typically represented as a round control to distinguish from the square
checkbox control.
Group boxes display frames around their contained controls and can display text in a caption, as
you see in below figure.
You set the group box's caption with the Text property.
AutoSize Sets/gets a value specifying if the height of the control automatically adjusts
when the font in the control is changed.
List boxes display a list of items from which the user can select one or more.
If there are too many items to display at once, a scroll bar automatically appears to let the user
scroll through the list.
48 VB.NET Notes
Figure: A list box control.
Properties:
• To keep track of selected item in the list box, the SelectedIndex property.
• The SelectedItem property is similar to SelectedIndex, but returns the object
corresponding to the item itself.
• The items in list boxes are stored in the Items collection.
• The Items.Count property holds the number of items in the list.
• The SelectedItems property to access the selected items.
• You also can scroll list boxes horizontally when you set the MultiColumn property to
True.
• When the ScrollAlwaysVisible property is set to True, a scroll bar always appears.
Methods:
• To add or delete items in a ListBox control at run time, you can use the Items.Add,
Items.Insert, Items.Clear, or Items.Remove methods.
• You can add and remove items to the list by using the Items property at design time.
• The FindString and FindStringExact methods enable you to search for an item in the
list that contains a specific search string.
Property Means
Text Gets the text of the selected item in the list box.
Items Returns a collection of the items of the list box.
SelectedItem Gets/sets the selected item in the list box.
SelectedItems Gets a collection containing the list box's selected items.
SelectedIndex Gets/sets the index of the list box's currently selected item.
49 VB.NET Notes
Table: public properties of ListBox objects.
Property Means
SelectedIndices Gets a collection that contains the indices of all selected items in the list
box.
ColumnWidth Gets/sets column width; use with multicolumn list boxes.
MultiColumn Gets/sets if the list box supports multiple columns.
HorizontalScrollbar Gets/sets if a horizontal scroll bar is displayed in the list box.
ScrollAlwaysVisible Gets/sets if a vertical scroll bar is always shown.
Sorted Gets/sets if the items in the list box are sorted. The sort is alphabetical.
The Windows forms combo box control is used to display data in a drop-down combo box.
• The top part is a text box that allows the user to type in all or part of a list item.
• The other part is a list box that displays a list of items from which the user can select one
or more.
Properties
• You can set and access the text in a combo box's text box with its Text property.
• Use the SelectedIndex property to get the selected list item.
50 VB.NET Notes
• Use the SelectedItem property, which is similar to SelectedIndex, but returns the item
itself (often a string value).
• The Items.Count property reflects the number of items in the list.
Methods
To add or delete items in a ListBox control, use the Items.Add, Items.Insert, Items.Clear,
Items.AddRange, or Items.Remove method. Or you can add and remove items to the list by
using the Items property at design time.
Picture boxes are used to display graphics from a bitmap, icon, JPEG, GIF or other image file
type. You can see a picture box at work in below figure.
51 VB.NET Notes
Figure: A picture box control.
To display an image in a picture box, you can set the Image property to the image you want to
display, either at design time or at run time.
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.PictureBox
Property Means
BorderStyle Gets/sets the border style for the picture box.
Image Gets/sets the image that is in a picture box.
52 VB.NET Notes
Table: public events of PictureBox objects.
Event Means
SizeModeChanged Occurs when SizeMode changes.
Note that the notable properties, methods, and events of PictureBox inherits from the Control
class are.
AutoSize Sets/gets a value specifying if the height of the control automatically adjusts
when the font in the control is changed.
53 VB.NET Notes
public events of PictureBox objects.
MouseUp Occurs when the mouse pointer is over the form and a mouse button
is released.
MouseDown Occurs when the mouse pointer is over the form and a mouse button
is pressed.
MouseMove Occurs when the mouse pointer is moved over the form.
1. Horizontal and
2. Vertical.
• The Scroll event, which happens continuously as the scroll bar is scrolled, and
• The ValueChanged event, which occurs every time the scroll bar's value changes by
even one unit.
• Use the Minimum and Maximum properties to set the range of values the user can select
using the scroll bar.
• The LargeChange property sets the scroll increment that happens when the user clicks in the
scroll bar but outside the scroll box.
• The SmallChange property sets the scroll increment when the user clicks the scroll arrows at
each end of the scroll bar.
• The default values for the Minimum, Maximum, SmallChange, and LargeChange values
are 0, 100, 1, and 10 respectively.
• You get the actual setting of a scroll bar with its Value property.
There are two types of scroll bars, horizontal ones (HScrollBar) and vertical ones (VScrollBar).
Here are the class hierarchies for both:
System.Object
54 VB.NET Notes
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ScrollBar
System.Windows.Forms.HScrollBar
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ScrollBar
System.Windows.Forms.VScrollBar
55 VB.NET Notes
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
HScrollBar1.Minimum = 0
HScrollBar1.Maximum = 10
VScrollBar1.Minimum = 0
VScrollBar1.Maximum = 10
End Sub
When the date and/or time changes, a ValueChanged event occurs, which I handle in the
Pickers example. You can get the new, selected date and time with the Text property of the
control.
Ex:
Public Class DateTimePickerExample
Private Sub DateTimePicker1_ ValueChanged (ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles DateTimePicker1.ValueChanged
MsgBox("Date Selected: " & DateTimePicker1.Text)
End Sub
56 VB.NET Notes
End Class
Output:
Class Hierarchy:
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.MonthCalendar
You can find the more notable public properties of the MonthCalendar class in Table 8.14, the
more notable methods in Table 8.15, and the more notable events in Table 8.16. Note that as
with other Windows forms controls, I am not listing the notable properties, methods, and events
MonthCalendar inherits from the Control class, such as the Click event—you can see all that
in Tables 5.1, 5.2, and 5.3, Chapter 5.
57 VB.NET Notes
Table 8.14: Noteworthy public properties of MonthCalendar objects.
Property Means
MaxDate Gets/sets the maximum possible date.
MinDate Gets/sets the minimum possible date.
TodayDate Gets/sets today's date.
TitleBackColor Gets/sets the back color of the calendar's title area.
TitleForeColor Gets/sets the fore color of the calendar's title area.
SelectionStart Gets/sets the start date of a selected range of dates.
SelectionEnd Gets/sets the end date of a selected range.
ShowToday Gets/sets if today's date is shown at the bottom of the control.
ShowTodayCircle Gets/sets if today's date should appear inside a circle.
Tool Tips
• Tool tips are small windows that appear with explanatory text when you let the mouse rest on
a control or window.
• To give quick help when the mouse rests on an item, tool tips are used.
Timers are not controls but components, and they do not appear in a window at run time.
At design time, they appear in the component tray underneath the form you've added them to.
58 VB.NET Notes
Setting a Timer's Interval
Setting a timer's interval—the time between Tick events—is easy; just set the timer's Interval
property. This property is measured in milliseconds, and the minimum setting is 1. For an
example of timers at work, take a look at "Handling Timer Events—and Creating an Alarm
Clock."
The Start and Stop methods are used to start & stop the timer.
For an example of timers at work, take a look at the next solution "Handling Timer Events—and
Creating an Alarm Clock."
Ex:
Public Class TimerExample
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Timer1.Start()
End Sub
Output:
59 VB.NET Notes
17.What is progress bar? Explain methods, properties and events.
Write a note on progress bar.
Progress bars are those simple controls that show the progress of some operation by displaying
rectangles in a horizontal bar, as you see in the below figure, which is the ProgressBars example.
In this case, the progress bar is being drawn using timer events that start when you click the Start
button.
60 VB.NET Notes
The main properties of a progress bar are Value, Minimum, and Maximum.
Class hierarchy:
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ProgressBar
61 VB.NET Notes
public methods of ProgressBar objects.
Method Means
Increment Increments the position of the progress bar by a given amount.
PerformStep Increments the value of the progress bar by the Step property.
Here's an example, where it uses a timer to steadily increment the Value property of
ProgressBar1, having already set the Minimum and Maximum properties. The action starts
when the user clicks a button labeled Start that enables the timer:
Output:
62 VB.NET Notes
10 Marks Questions
1. What is the use of combo box? Explain different types of events in combo
box.
The Windows forms combo box control is used to display data in a drop-down combo box.
• The top part is a text box that allows the user to type in all or part of a list item.
• The other part is a list box that displays a list of items from which the user can select one
or more.
Properties
63 VB.NET Notes
• You can set and access the text in a combo box's text box with its Text property.
• Use the SelectedIndex property to get the selected list item.
• Use the SelectedItem property, which is similar to SelectedIndex, but returns the item
itself (often a string value).
• The Items.Count property reflects the number of items in the list.
Methods
To add or delete items in a ListBox control, use the Items.Add, Items.Insert, Items.Clear,
Items.AddRange, or Items.Remove method. Or you can add and remove items to the list by
using the Items property at design time.
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ListControl
System.Windows.Forms.ComboBox
Properties of ComboBox objects
64 VB.NET Notes
Table: public methods of ComboBox objects.
Method Means
BeginUpdate Turns off visual updating of the combo box until the EndUpdate method is
called.
EndUpdate Resumes visual updating of the combo box.
FindString Finds the first item in the combo box that begins with the indicated string.
FindStringExact Finds the item that matches the indicated string exactly.
GetItemText Gets an item's text.
Note that as with other Windows forms controls, I am not listing the notable properties,
methods, and events ComboBox inherits from the Control class, such as the Click event.
65 VB.NET Notes
public properties of ComboBox objects.
Property Means
AutoSize Sets/gets a value specifying if the height of the control automatically adjusts
when the font in the control is changed.
There are three types ComboBox. You select which type you want with the combo box's
DropDownStyle
Here are the settings for the combo box DropDownStyle property- these are members of the
ComboBoxStyle enumeration:
66 VB.NET Notes
• DropDownList-This style allows selection only from the drop-down list.
At run time use the Items.Insert,Items.Add, and Items.AddRange methods to add items to the
list part of a combo box.
TextChanged Events
When the user changes the text in a combo box, a TextChanged event occurs, just as it does
when the user types in a standard text box. You can read the new text in the text box with the
Text property; for example, here's how we display the new text in the combo box every time the
user changes that text by typing:
SelectedIndexChanged Events
When the selection changes in a combo box, a SelectionChanged event happens, and you can
use the SelectedIndex and SelectedItem properties to get the index of the newly selected item
and the item itself:
67 VB.NET Notes
End Sub
Output:
Click Events
You also can 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 combo's SelectedIndex property,
which holds the index of the clicked item, or get that item directly using the SelectedItem
property, because when you click an item, it is made the new selected item in the text box.
End Sub
68 VB.NET Notes
Getting the Current Selection in a Combo Box
When you make a selection in a combo box, that new selection appears in the combo box's text
box, so it's easy to get the text of the current selection—you just use the combo box's Text
property.
You also can use the SelectedIndex and SelectedItem properties to get the index of the selected
item and the selected items itself. Here's how I display information about the currently selected
item in a combo box in the ComboBoxes example when the user clicks the "Get selected" button:
Output:
At run time,
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
69 VB.NET Notes
ComboBox1.Sorted = True
End Sub
Output:
70 VB.NET Notes
VB.net Chapter 5 Data Access with
ADO.NET
Define ADO.Net ?
ADO.Net is a Data access technology from Microsoft
.Net framework, Which provides communication
between relational and non-relational systems
through a common set of components.
A collection of records—that is, rows of records, where each column is a field— becomes a
table. What, then, is a database?
Type of database
71 VB.NET Notes
2. Relational database.
For example, if I wanted to get access to the data in the table in Figure 20.1,
1. I would first create a connection to the database the table was stored in,
2. Then create an adapter with the SQL to retrieve that table (for example, if the table was
named students, that SQL might be "SELECT * FROM students"),
3. Then fill a DataSet object using that adapter.
So those are the three objects that it's essential to know about:
72 VB.NET Notes
Below Figure shows an overview of ADO.NET data objects.
73 VB.NET Notes
• Data adapters can read, add, update, and delete records in a data source.
• You typically configure a data adapter with SQL to execute against the data source.
• The two types of data adapters are OleDbDataAdapter and SqlDataAdapter objects.
3. Command objects
To read, add, update, and delete records in a data source, a data adapter contains command
objects such as SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand.
4. Datasets
• Datasets store data in a disconnected cache.
• The structure of a dataset is similar to that of a relational database.
• It gives you access to an object model of tables, rows, and columns, and it contains
constraints and relationships defined for the dataset.
• Datasets are supported with DataSet objects.
5. DataTable objects
• DataTable objects hold a data table from a data source.
• Data tables contain two important properties:
o Columns, which is a collection of the DataColumn objects that represent the
columns of data in a table,
o Rows, which is a collection of DataRow objects, representing the rows of data in
a table.
7. Data views
• Data views represent a customized view of a single table that can be filtered, searched, or
sorted.
• A data view, supported by the DataView class, is a data "snapshot" that takes up few
resources.
8. Constraint objects
• Datasets support constraints to check data integrity.
• A constraint, supported by the Constraint class, is a rule that can be used when rows are
inserted, updated, or deleted to check the affected table after the operation.
• There are two types of constraints:
o unique constraints check that the new values in a column are unique throughout
the table,
o foreign-key constraints specify how related records should be updated when a
record in another table is updated.
74 VB.NET Notes
9. DataRelation objects
DataRelation objects specify a relationship between parent and child tables, based on a key that
both tables share.
DataRow objects correspond to a particular row in a data table. You use the Item property to get
or set a value in a particular field in the row.
DataColumn objects correspond to the columns in a table. Each object has a DataType property
that specifies the kind of data each column contains, such as integers or string values.
75 VB.NET Notes
• In Visual Basic, the Server Explorer lets you work with connections to various data
sources.
• The Server Explorer lets you create and examine data connections, including connections
to Web servers; you can see connections to various databases in the Server Explorer
already.
• You can see the Server Explorer in Figure 20.3, where I've docked it to the left edge of
the Visual Basic IDE.
76 VB.NET Notes
In the EasyAccess example, I'm going to display the data from the authors table in the Microsoft
SQL Server's pubs sample database, so we'll need a connection to that database, for example pub
is the name of the database.
To create that connection, right-click the Data Connections icon in the Server Explorer and select
the Add Connection item, or use the Tools|Connect to Database menu item. Doing so opens the
Data Link Properties dialog you see in Figure 20.4.
In the Data Link Properties dialog, you can enter the name of the server you want to work with,
as well as your login name and password, if applicable. (Here, I'm going to use Windows NT
integrated security, because SQL Server is on the same machine as VB .NET in my case, but you
77 VB.NET Notes
can choose a server name and enter a user name and password in the Data Link Properties dialog,
if you prefer.)
You can choose a database already on the server with the "Select the database on the server"
option, or another database file with the "Attach a database file as a database name" option. In
this case, we'll use the pubs example database that comes with SQL Server, so select the first
option here and choose the pubs database, as you see in Figure 20.5.
What if you're not using SQL Server, but, say, Oracle to connect to a database? In that case, you
click the Provider tab in the Data Link Properties dialog, as you see in Figure 20.6, and select the
type of provider you're working with—Oracle, MS Jet, and so on (the default is SQL Server).
78 VB.NET Notes
Then you go back to the Connection tab and choose the specific database file you want to work
with. For an example, see "Connecting to an MS Jet Database" in this chapter.
When you've specified the database file to work with, click the Connection tab and the Test
Connection button you see in Figure 20.5. If the connection is working, you'll see a message box
with the message "Test connection succeeded" (and if not, a message box will appear, explaining
what went wrong).
When the connection is set, click the OK button to close the Data Link Properties dialog. Doing
so adds a new connection to the pubs database to the Server Explorer, as you see in Figure 20.3.
You can open that connection (assuming, in this case, that SQL Server is running) and take a
look what tables are in the database, as you also see in Figure 20.3. Our data connection is ready
79 VB.NET Notes
to work with. Note that this connection is now part of your Visual Basic working environment;
it's not specific to the application you're working on at the moment. You can access this
connection in the Server Explorer at any time, even when working on other applications.
2. Drag a table from the Server Explorer onto a form; this adds a data connection and a
data adapter to the form.
In this example, we want to display the data in the authors table of the pubs database, and this is
where the Server Explorer makes life easy for us. To create both the data connection and adapter
objects we'll need to work with this table, just drag the authors table onto the main form.
This automatically creates the SqlConnection1 and SqlDataAdapter1 objects you see in the
component tray in Figure 20.7. (If we had been working with another data provider, Visual Basic
would have created OleDbConnection1 and OleDbDataAdapter1 objects.)
3. Generate a dataset.
That was easy enough—Visual Basic created the data connection and data adapter objects we
need. (Note that in this case we wanted the whole authors table, which means we could simply
drag that table onto a form. If we wanted to work with only specific fields, we'd have to generate
an SQL query in a data adapter object ourselves, and we'll do that by dragging a data adapter
80 VB.NET Notes
onto a form in the next example.) Now it's time to generate the dataset that holds the data from
the data adapter. To do that, just select the Data|Generate Dataset menu item, or right-click
SqlDataAdapter1 and select the Generate Dataset menu item. This displays the Generate
Dataset dialog you see in Figure 20.8.
In this case, click the New option to create a new dataset. I'll stick with the default name given to
this new dataset object, DataSet1, as you see in the figure; make sure the authors table
checkbox is checked, as well as the "Add this dataset to the designer" checkbox, then click OK.
Doing so adds a new dataset, DataSet11, to the form designer's component tray, as you see in
Figure 20.9. This is the dataset we'll work with.
81 VB.NET Notes
4. Bind the dataset to controls.
To display the data in the dataset, I'll use a data grid control, which we'll see more of in the next
chapter (see "Using the DataGrid Class" in Chapter 21). This control is designed to display
entire database tables, so find the DataGrid tool in the Window Forms tab in the toolbox, and
drag a new data grid to the main form, sizing it to fit the form. (You can use its Dock property to
make that sizing easy if you prefer.)
Set the data grid's DataSource property to Data11 (not DataSet11.authors, which also will be
displayed as an option in the Properties window), and its DataMember property to authors,
which will be displayed automatically as an option when you click that property. This connects
the data in the dataset to the data grid.
The final step (which wasn't necessary in Visual Basic 6.0 or earlier) is that you must specifically
use the data adapter to fill the dataset with data. The reason you must do this is because the
dataset is disconnected from the data provider; it just holds a local copy of the data you're
working with. To fill the dataset with data from the data adapter (and remember that our data
adapter is already set up to get its data from the authors table of the pubs database), you use the
data adapter's Fill method. Here's the code to add to the Form1_Load method; this code clears
the dataset and then fills it with data from the data adapter:
82 VB.NET Notes
DataSet11.Clear()
SqlDataAdapter1.Fill(DataSet11)
End Sub
And that's it—now run the application. You can see the results in Figure 20.10, where you see
the data in the pubs database's authors table displayed, showing the data for the various fields in
that table, such as au_id (this is the name Microsoft has given to this field when it created this
table—it's a contraction of "author ID"), au_lname (for "author last name"), and so on. (Note that
not all the data can be displayed in the data grid at once, so scroll bars appear at right and at
bottom of this control.)
That gives us just about the easiest, most painless introduction to working with data access in
Visual Basic .NET. Notice, however, that this was a special example, because here, we wanted to
look at the entire authors table all at once. But what if we had wanted to look at only a few
fields of the authors table? In that case, we would have to configure the data adapter ourselves,
and I'll show how that works with another example now.
83 VB.NET Notes
2. Drag an OleDBAdaptor or SQLAdaptor object onto a form; creates connection and
adaptor objects.
3. Use the Data Adapter Configuration Wizard to configure the data adapter and
create the SQL you want.
4. Generate a dataset.
5. Bind the dataset to controls.
6. Fill the dataset in code.
In the previous example, we dragged an entire data table from the Server Explorer to a form, but
often you'll want to look at only a few fields in a table, or otherwise customize what you want to
do with a table before working with its data. To do that, you can create a data adapter yourself.
It's easy to do.
To see how this works, just click the Data tab in the toolbox now. In this case, I'll drag an
OleDbDataAdapter object from the toolbox to the main form. (I'm going to use an
OleDbDataAdapter here only because we already used an SqlDataAdapter in the previous
example—the rest of the operations here are the same no matter what type of data adapter you
use.)
3. Use the Data Adapter Configuration Wizard to configure the data adapter and create
the SQL you want.
Doing so opens the Data Adapter Configuration Wizard that you see in Figure 20.11. This
wizard will let you customize your data adapter as you want, which usually means creating the
SQL statement this adapter will use. (You can always right-click a data adapter and select the
Configure Data Adapter menu item to change an adapter's configuration, including its SQL.)
84 VB.NET Notes
Click the Next button in the Data Adapter Configuration Wizard to choose the data connection
you want to use, as you see in Figure 20.12. You can use an existing data connection of the type
we've already created, or click the New Connection button to create a new data connection.
(Clicking this button will open the Data Link Properties dialog that we've already used to create
a new connection; you can see this dialog in Figure 20.5.) In this case, I'll use the connection
we've already made to the pubs database, as you see in Figure 20.12.
85 VB.NET Notes
Click Next to choose a query type for the adapter, as you see in Figure 20.13. Here, I'll specify
that we're going to create an SQL statement, as you see in the figure, but notice that you can
either create new or use existing stored SQL procedures. (Using stored procedures is a common
SQL technique, and they're great, because they not only hold the SQL you want to use, but they
also are stored in the database and can be used over and over by many different applications.)
86 VB.NET Notes
Click Next to display the dialog you see in Figure 20.14, where we'll generate the SQL statement
we'll use in this data adapter.
87 VB.NET Notes
To make writing the SQL easy, click the Query Builder button now. This displays the Add Table
dialog that you see in Figure 20.15. An SQL statement can work with several tables at the same
time (as when you join them together), so here you select the tables you want to work with and
click the Add button. When you've selected all the tables you want to work with in this way,
click the Close button.
88 VB.NET Notes
In this example, we're going to display a few fields from the authors table, so just select that
table and click Add in the Add Table dialog, then click Close. This opens the Query Builder
itself, as you see in Figure 20.16.
89 VB.NET Notes
At top in Figure 20.16, you can see a window displaying fields in the authors table. If you were
working with more than one table, you'd see them all open in windows in the query builder, and
you'd also see lines indicating any relations connecting primary and foreign keys between the
tables (see "Using Relational Databases" in this chapter for an example). You add a field to the
generated SQL statement by clicking the checkboxes in a table's window. In Figure 20.16, I've
checked the au_id, au_lname, and au_fname fields. (Again, note that these are the names
Microsoft gave to these fields when the authors table was created— these names are not created
by Visual Basic.) You also can select all fields in a table by checking the checkbox labeled with
an asterisk (*), which specifies all fields in SQL. Note that you must select at least one field
when creating the SQL for a data adapter, or the Query Builder won't be able to create working
SQL.
Now click the OK button, creating the SQL statement you see in the Data Adapter Configuration
Wizard in Figure 20.17. This is the SQL this adapter will use to retrieve data from the database,
as well as update the database when you want to, delete records if you want to, and so on.
90 VB.NET Notes
When you click Next in the Data Adapter Configuration Wizard, the wizard configures the data adapter
and reports on the results, as you see in Figure 20.18. We're done—just click the Finish button to dismiss
the Data Adapter Configuration Wizard.
91 VB.NET Notes
4. Generate a dataset.
And
5. Bind the dataset to controls.
That creates the data adapter we'll need, OleDataAdapter1. Now create a new dataset using this
data adapter, as we've done before (i.e., use the Data|Generate Dataset menu item), and connect
the new dataset to a data grid using the DataSource and DataMember properties, also as before.
Previously, I filled the data grid with data from the data adapter in the form's load event, but
you'll often see "Load" buttons that the user can click to load data into the dataset (and so also
the data grid), so I'll use a Load button here, with this code:
The user can edit the data in a data grid directly, and update the database with it if you want to
allow such operations. To make that happen, I'll add a button with the caption "Update" and use
the data adapter's Update method—like this—to update the database with the edited data in the
data grid:
When the user edits the data in the data grid control, that control automatically updates the
dataset. To send the new data back to the database, you have to use the data adapter's Update
method, as we're doing here. And that's it—you can see the results in Figure 20.19, where just
the fields we selected are displayed. You can, of course, do a lot more with SQL than just select
a few fields, but this example has shown us how to use SQL in data adapters to get the results we
want.
92 VB.NET Notes
Now we've seen for ourselves the main objects you use in Visual Basic .NET data access, and
we've put them to work, giving us some direct familiarity with the whole process. Armed with
that firsthand knowledge, we're ready to take a look at the larger picture now, seeing what
objects make up the Visual Basic data access world.
For example, to get all the records in the Customers table, using the wildcard character *:
This returns a dataset that holds all the records in the Customers table.
93 VB.NET Notes
Also the SELECT statement is used to select specific fields from a table, like this, where I'm
selecting the CustomerID, Address, and City fields of all the records in the Customers table:
This returns a dataset that holds all the records in the Customers table, and each record will have
a CustomerID, Address, and City field.
For example, to select all the records in the Customers table where the City field holds
"Boston", you can execute this statement:
For example, select all the records from the Customers table where the CustomerID record starts
with the letter H (the CustomerID field is alphabetic, not numeric, in this table):
Note the use of wildcard characters: "H*" and "I*". Using these wildcards lets you specify that
you want all the CustomerID values that start with the letter H.
For example, to get records that have values in the City field that match Boston or York:
For example, select all the records from the Customers table where the City field matches the
wildcard string "Los*":
94 VB.NET Notes
Using the DISTINCT Clause
The query returns only distinct values in the specified column. In other words, it removes the duplicate
values in the column from the result set.
For example,
The City field cannot be either Boston or York, and there must be some value in the Fax field
(note that I'm using the NULL keyword to test if there's anything in a field):
SELECT * FROM Customers WHERE City NOT IN ("Boston","York") AND Fax IS NOT NULL
95 VB.NET Notes
• SUM— adds values over records.
• MIN— finds the minimum value of a set of records.
• MAX— finds the maximum value of a set of records.
• AVG— finds the average value of a set of records.
For example, to group only records with cities that begin with "Los":
For example, deleting every record from the Customers table that has City values that are not
Boston or York:
For example, to chang the City to Boston in all records where it's York now:
96 VB.NET Notes
Joining Tables
The SQL Joins clause is used to combine records from two or more tables in a
database.
LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left
table.
FULL JOIN − returns rows when there is a match in one of the tables.
SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming
at least one table in the SQL statement.
CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more
joined tables.
Ex:
97 VB.NET Notes