After an item has been selected, to make a different
selection, the user would click another. The new clicked item becomes selected
or highlighted; the previously selected item looses its highlighting attribute.
The user can also change the selection by pressing the up or down arrow keys.
List boxes are categorized in two types: single and
multi-selection. The second category allows a user to select more than one item
by pressing Ctrl to select items at random or by pressing Shift to select items
in a range.
One of the main reasons for using a list box is to display a
list of items to the user. Sometimes the list would be very large. If the list
is longer than the available client area of the control, the control would be
equipped with a scroll bar that allows the user to navigate up and down to
access all items of the list. You will have the option of deciding how many
items to display on the list.
Practical Learning: Introducing List Boxes
|
|
- Start Microsoft Visual Basic and create a new Windows Application named
MusicalInstrumentStore1
- In the Solution Explorer, right-click Form1.cs and click Rename
- Type MusicStore.vb and press Enter
To support list boxes, the .NET Framework provides the
ListBox class. At design time, to add a list box to an application, from the
Common Controls section of the Toolbox, click the ListBox control and click the
form or the control that will host it. To programmatically create a list box,
declare a variable of type ListBox, use the new operator to allocate memory it,
and add it to the Controls property of its eventual parent.
Imports System.Windows.Forms
Module Exercise
Public Class Starter
Inherits Form
Private lbxFamily As ListBox
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
lbxFamily = New ListBox()
Controls.Add(lbxFamily)
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
|
In our applications, the names of the list-based
controls will be in plural. This is not a rule and it is not based on
any preconceived standard. |
Practical Learning: Creating List Boxes
|
|
- Design the form as follows:
|
Control |
Text |
Name |
Other Properties |
GroupBox |
|
Musical Instrument Selection |
|
|
Label |
|
Categories |
|
|
Label |
|
Types |
|
|
Label |
|
Items |
|
|
ListBox |
|
|
lbxCategories |
|
ListBox |
|
|
lbxTypes |
|
ListBox |
|
|
lbxItems |
|
GroupBox |
|
Selected Items |
|
|
Label |
|
|
Part # |
|
Label |
|
|
Description |
|
Label |
|
|
Unit Price |
|
Label |
|
|
Qty |
|
Label |
|
|
Sub Total |
|
TextBox |
|
|
txtPartID1 |
|
TextBox |
|
|
txtDescription1 |
|
TextBox |
|
0.00 |
txtUnitPrice1 |
TextAlign: Right |
TextBox |
|
0 |
txtQantity1 |
TextAlign: Right |
TextBox |
|
0.00 |
txtSubTotal1 |
TextAlign: Right |
Button |
|
Rmv |
btnRemove1 |
|
TextBox |
|
|
txtPartID2 |
|
TextBox |
|
|
txtDescription2 |
|
TextBox |
|
0.00 |
txtUnitPrice2 |
TextAlign: Right |
TextBox |
|
|
txtQuantity2 |
TextAlign: Right |
TextBox |
|
0.00 |
txtSubTotal2 |
TextAlign: Right |
Button |
|
Rmv |
btnRemove2 |
|
TextBox |
|
|
txtPartID3 |
|
TextBox |
|
|
txtDescription3 |
|
TextBox |
|
0.00 |
txtUnitPrice3 |
TextAlign: Right |
TextBox |
|
0 |
txtQuantity3 |
TextAlign: Right |
TextBox |
|
0.00 |
txtSubTotal3 |
TextAlign: Right |
Button |
|
Rmv |
btnRemove3 |
|
TextBox |
|
|
txtPartID4 |
|
TextBox |
|
|
txtDescription4 |
|
TextBox |
|
0.00 |
txtUnitPrice4 |
TextAlign: Right |
TextBox |
|
|
txtQuantity4 |
TextAlign: Right |
TextBox |
|
0.00 |
txtSubTotal4 |
TextAlign: Right |
Button |
|
Rmv |
btnRemove4 |
|
TextBox |
|
|
txtPartID5 |
|
TextBox |
|
|
txtDescription5 |
|
TextBox |
|
0.00 |
txtUnitPrice5 |
TextAlign: Right |
TextBox |
|
0 |
txtQuantity5 |
TextAlign: Right |
TextBox |
|
0.00 |
txtSubTotal5 |
TextAlign: Right |
Button |
|
Rmv |
btnRemove5 |
|
TextBox |
|
|
txtPartID6 |
|
TextBox |
|
|
txtDescription6 |
|
TextBox |
|
0.00 |
txtUnitPrice6 |
TextAlign: Right |
TextBox |
|
0 |
txtQuantity6 |
TextAlign: Right |
TextBox |
|
0.00 |
txtSubTotal6 |
TextAlign: Right |
Button |
|
Rmv |
btnRemove6 |
|
Button |
|
Close |
btnClose |
|
Label |
|
|
Order Total: |
|
TextBox |
|
0.00 |
txtTotalOrder |
TextAlign: Right |
|
- Save the form
Like every control, when creating a list box, make sure you
give it a name. Once the list box is positioned on a container, as done with
other controls, you can move it by clicking and dragging the control. You can
also resize it using any of the techniques we learned to add, position, move,
and resize controls. If the list will cover many items, design it so its height
can display 8 items at a time. Otherwise, for a list of 8 or less items, use
only the necessary height that would accommodate all of the items.
Adding Items to a List Box
|
|
The most important characteristic of a list box is the list
of items it contains. This list is represented by the Items property. The Items
list is created and managed by a ListBox-nested class named
ObjectCollection. ObjectCollection is a collection class that
implements the IList, the ICollection, and the IEnumerable
interfaces.
At design time, to create a list of items, access the
Properties window of the list box and click the ellipsis button of the Items
field. This would open the String Collection Editor:
In the empty window, you can type an item, press Enter, add
another, and so on. After creating the list, you can click OK. To
programmatically add an item to the list, access the Items property, call
its Add() method, and pass the new item. You can do this continually for
each item. Here are examples:
Public Sub InitializeComponent()
lbxFamily = New ListBox()
lbxFamily.Location = New Point(12, 12)
lbxFamily.Items.Add("Son")
lbxFamily.Items.Add("Daughter")
lbxFamily.Items.Add("Father")
lbxFamily.Items.Add("Mother")
Controls.Add(lbxFamily)
End Sub
This would produce:
You can also first create an array of items and then add
that array to the collection. To support this, the ObjectCollection class
provides the AddRange() method. Here is an example:
Public Sub InitializeComponent()
lbxFamily = New ListBox()
lbxFamily.Location = New Point(12, 12)
lbxFamily.Items.Add("Son")
lbxFamily.Items.Add("Daughter")
lbxFamily.Items.Add("Father")
lbxFamily.Items.Add("Mother")
Dim strMembers As String() = {"Niece", "Nephew", "Uncle"}
lbxFamily.Items.AddRange(strMembers)
Controls.Add(lbxFamily)
End Sub
This would produce:
If you use either the Add() or the AddRange()
method to add an item or a group of items, the item or the group would be added
to the end of the list, if a list exists already. To insert a new item somewhere
inside of the list, call the Insert() method.
Practical Learning: Adding Items to a List Box
|
|
- On the form, click the Categories list box
- In the Properties window, click Items and click its ellipsis button
- Type Guitars and press Enter
- Type Bass and press Enter
- Complete the list to have the following items:
Guitars
Bass
Keyboards
Drums & Percussion
Band & Orchestra
Recording & Sound
Folk Instruments
Books & Videos
Accessories |
- Click OK
- To programmatically add items to the list boxes, on the form,
double-click an unoccupied area to access its Load event and implement it as
follows:
Private Sub MusicStore_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
lbxTypes.Items.Add("Electric Guitars")
lbxTypes.Items.Add("Acoustic Guitars")
lbxTypes.Items.Add("Acoustic-Electric Guitars")
lbxTypes.Items.Add("Amplifiers")
lbxTypes.Items.Add("Effects")
lbxTypes.Items.Add("Microphones")
lbxTypes.Items.Add("Accessories")
lbxTypes.Items.Add("Value Packages")
End Sub
|
- Execute the application to test it
- After using the form, close it and return your programming environment
- To create a class, on the main menu, click Project -> Add Class...
- In the Templates list, make sure Class is select.
Set the name to PartDescription and click Add
- Complete the class as follows:
Imports System.Net.Mail
Public Class PartDescription
Private number As String
Private discr As String
Private uprice As Double
Property PartNumber() As String
Get
Return number
End Get
Set(ByVal value As String)
number = value
End Set
End Property
Property PartName() As String
Get
Return discr
End Get
Set(ByVal value As String)
discr = value
End Set
End Property
Public Property UnitPrice() As Double
Get
Return uprice
End Get
Set(ByVal value As Double)
uprice = value
End Set
End Property
Public Sub New()
number = ""
discr = ""
uprice = 0.0
End Sub
Public Sub New(ByVal nbr As String, _
ByVal name As String, _
ByVal price As Double)
number = nbr
discr = name
uprice = price
End Sub
Public Overrides Function ToString() As String
Return PartNumber & " " & _
PartName & " " & _
UnitPrice.ToString()
End Function
End Class
|
- Access the MusicStore.vb file and create a few arrays as follows:
Public Class MusicStore
Private CatBass() As String
Private CatKeyboard() As String
Private CatDrums() As String
Private CatBand() As String
Private CatAccessories() As String
Private ElectricGuitars() As PartDescription
Private AcousticGuitars() As PartDescription
Private ElectricBasses() As PartDescription
Private AcousElectBasses() As PartDescription
Private Pianos() As PartDescription
Private Synthetizers() As PartDescription
Private Books() As PartDescription
Private Cables() As PartDescription
Private Sub MusicStore_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
lbxTypes.Items.Add("Electric Guitars")
lbxTypes.Items.Add("Acoustic Guitars")
lbxTypes.Items.Add("Acoustic-Electric Guitars")
lbxTypes.Items.Add("Amplifiers")
lbxTypes.Items.Add("Effects")
lbxTypes.Items.Add("Microphones")
lbxTypes.Items.Add("Accessories")
lbxTypes.Items.Add("Value Packages")
CatBass = New String() { _
"Electric Bass", "Acoustic-Electric Bass", _
"Amplifiers", "Effects", "Accessories"}
CatKeyboard = New String() { _
"Pianos", "Organs", "Synthesizers", _
"Portable", "Workstations", "Arrangers", _
"Stands", "Amps", "Pedals", "Accessories"}
CatDrums = New String() { _
"Acoustic Drums", "Cymbals", _
"Electronic Percussion", "World Percussion"}
CatBand = New String() { _
"Trumpets", "Trombones", "Saxophones", _
"Clarinets", "Flutes", "Baritones", "Tubas", _
"Oboes", "Recorders", "Accessories"}
CatAccessories = New String() { _
"Headphones", "Strings", "Slides", "Metronomes", _
"Tuners", "Music Stands", "Cases", "Cables", _
"Hearing Protection", "Electric Guitar Bags", _
"Guitar Pedals", "Cleaning/Care"}
ElectricGuitars = New PartDescription() _
{ _
New PartDescription("293027", _
"Gibson Les Paul Vintage Solid Guitar", _
850.75), _
New PartDescription("972355", _
"Fender Standard Stratocaster Electric Guitar", _
435.95), _
New PartDescription("390057", _
"Gibson Les Paul Standard Left-Handed 50s Neck Electric Guitar", _
2400.0), _
New PartDescription("297548", _
"Schecter C-1 Hellraiser Electric Guitar", _
649.95), _
New PartDescription("284704", _
"Gretsch Guitars G5120 Electromatic Hollowbody Electric Guitar", _
595.95), _
New PartDescription("293472", _
"Rickenbacker 360 12-String Electric Guitar", _
2195.95), _
New PartDescription("208476", _
"Steinberger Synapse ST-2FPA TranScale Custom Electric Guitar", _
1045.5), _
New PartDescription("253463", _
"Gibson EDS 1275 Double-Neck Electric Guitar", _
3050.25), _
New PartDescription("225747", _
"Fender American Stratocaster Left-Handed Electric Guitar", _
950.5), _
New PartDescription("274875", _
"Epiphone Dot Studio Semi-Hollow Electric Guitar", _
295.25) _
}
AcousticGuitars = New PartDescription() _
{ _
New PartDescription("224885", _
"Epiphone Hummingbird Acoustic Guitar", 245.55), _
New PartDescription("283407", _
"Dean V Coustic Thin Body Acoustic-Electric Guitar", 205.5), _
New PartDescription("275111", _
"Yamaha FG720S 12-String Acoustic Guitar", 325.55), _
New PartDescription("249036", _
"Rogue RA-100D Dreadnought Acoustic Guitar", 82.95), _
New PartDescription("285507", _
"Alvarez RD8 Regent Series Dreadnought Acoustic Guitar", 220.5), _
New PartDescription("283746", _
"Epiphone EJ-200 Acoustic Guitar", 350.5) _
}
ElectricBasses = New PartDescription() _
{ _
New PartDescription("248780", _
"Epiphone Thunderbird IV Bass", 325.5), _
New PartDescription("203487", _
"Squier® Vintage Modified '70s Jazz Bass", 305.95), _
New PartDescription("204633", _
"Fender Standard Precision Bass", 450.75), _
New PartDescription("297548", _
"Music Man StingRay 5-String Bass Guitar", 1485.95) _
}
AcousElectBasses = New PartDescription() _
{ _
New PartDescription("248780", _
"Ibanez AEB10E Acoustic-Electric Bass Guitar with Onboard Tuner", _
335.5), _
New PartDescription("203487", _
"Dean Playmate EABC 5-String Cutaway Acoustic-Electric Bass", _
285.95), _
New PartDescription("204633", _
"Fender BG-32 Acoustic/Electric Bass Guitar", _
495.75), _
New PartDescription("634974", _
"Gibson Thunderbird IV Bass", 1500.0), _
New PartDescription("674950", _
"Rogue VB-100 Violin Bass", 255.95), _
New PartDescription("634742", _
"Squier Standard P Bass 4-String Bass", _
220.75), _
New PartDescription("637904", _
"Peavey Millennium BXP 4-String Bass", 210.95) _
}
Pianos = New PartDescription() _
{ _
New PartDescription("584603", _
"Williams ETUDE Console Piano", 450.95), _
New PartDescription("504724", _
"Rolan EP-760C Digital Piano w/Stand", 650.95) _
}
Synthetizers = New PartDescription() _
{ _
New PartDescription("582970", _
"Alesis ION 49-Key 1K DSP Synthesizer", 750.5), _
New PartDescription("524885", _
"Korg MicroKORG Synthesizer/Vocoder", 350.75), _
New PartDescription("549085", _
"Yamaha YDP223 Digital Piano", 1450.0), _
New PartDescription("529307", _
"Access Virus kc 5-Octave Synth", 1915.55) _
}
Dim Books = New PartDescription() _
{ _
New PartDescription("883670", _
"Alfred Guitar for the Absolute Beginner", _
16.55), _
New PartDescription("837654", _
"Hal Leonard Guitar Tab White Pages", 20.95), _
New PartDescription("843047", _
"Carl Fischer Guitar Grimoire Progressions and Improvisation", _
24.75), _
New PartDescription("845716", _
"Bill Edwards Publishing Fretboard logic Spc Ed.", _
17.95), _
New PartDescription("833427", _
"Walrus Productions Guitar Chord Poster", 6.85) _
}
Cables = New PartDescription() _
{ _
New PartDescription("188370", _
"Musician's Friend Professional Cable", _
4.55), _
New PartDescription("183614", _
"Monster Cable S-100 Straight Cable", 20.95), _
New PartDescription("143047", _
"Hosa TRS-TRS Stereo 1/4"" Cable", 4.65), _
New PartDescription("145716", _
"Mogami Silver Series Cable", 12.95) _
}
End Sub
End Class
|
- Save all
Selecting an Item in a List Box
|
|
To an item from a list box, the user must locate and click
the desired item. That item is said to have been selected. To programmatically
select an item, you can assign the index of the desired item to the
ListBox.SelectedIndex property. The indices of the items of a list box are
stored in a zero-based array. This means that the first item has an index of 0,
the second has an index of 1, and so on. Here is an example that will select the
fourth item of the list:
Public Sub InitializeComponent()
lbxFamily = New ListBox()
lbxFamily.Location = New Point(12, 12)
lbxFamily.Items.Add("Son")
lbxFamily.Items.Add("Daughter")
lbxFamily.Items.Add("Father")
lbxFamily.Items.Add("Mother")
Dim strMembers As String() = {"Niece", "Nephew", "Uncle"}
lbxFamily.Items.AddRange(strMembers)
lbxFamily.SelectedIndex = 3
Controls.Add(lbxFamily)
End Sub
This would produce:
After an item has been selected, to find out the index of
the item that is currently selected, get the value of the
ListBox.SelectedIndex property.
To select an item, the user can click it in the list box.
When an item has been clicked, the list box fires a SelectedIndexChanged
event. Because selecting an item is the most regularly performed operation on a
list box, SelectedIndexChanged is the default event of a list box. This
event is of type EventArgs which means that it does not provide any
significant information other than to let you know that an item has been
selected. Nonetheless, this event allows you to easily check if an item has been
selected and what item has been selected.
To fire a SelectedIndexChanged event and to test what item has been
selected in the list, you can double-click the list box.
The ListBox.SelectedIndex property allows you either
to select an item or to find out what item is selected, using its index, that
is, the numeric position of the item in the list. If you know the identity, such
as the name, of the item you want to select, or if you want to identify the
selected item based on its name, you can use the ListBox.SelectedItem
property instead. This member identifies the item instead of locating it.
By default, the user can select only one item in the list.
If you want the user to be able to select more than one item, change the value
of the SelectionMode property. This property is based on the
SelectionMode enumeration. After the user has selected more than one item,
to get the indexes of the items that are selected, you can access the
ListBox.SelectedIndices property which holds that list.
Practical Learning: Selecting an Item From a List Box
|
|
- In the Class Name combo box, select lbxCategories
- In the Method Name combo box, select SelectedIndexChanged and implement
the event as follows:
Private Sub lbxCategories_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles lbxCategories.SelectedIndexChanged
If lbxCategories.SelectedItem = CType("Guitars", Object) Then
lbxTypes.Items.Add("Electric Guitars")
lbxTypes.Items.Add("Acoustic Guitars")
lbxTypes.Items.Add("Acoustic-Electric Guitars")
lbxTypes.Items.Add("Amplifiers")
lbxTypes.Items.Add("Effects")
lbxTypes.Items.Add("Microphones")
lbxTypes.Items.Add("Accessories")
lbxTypes.Items.Add("Value Packages")
ElseIf lbxCategories.SelectedItem = CType("Bass", Object) Then
lbxTypes.Items.AddRange(CatBass)
ElseIf lbxCategories.SelectedItem = CType("Keyboards", Object) Then
lbxTypes.Items.AddRange(CatKeyboard)
ElseIf lbxCategories.SelectedItem = _
CType("Drums & Percussion", Object) Then
lbxTypes.Items.AddRange(CatDrums)
ElseIf lbxCategories.SelectedItem = _
CType("Band & Orchestra", Object) Then
lbxTypes.Items.AddRange(CatBand)
ElseIf lbxCategories.SelectedItem = _
CType("Books & Videos", Object) Then
lbxTypes.Items.Add("Books")
lbxTypes.Items.Add("DVDs")
ElseIf lbxCategories.SelectedItem = _
CType("Accessories", Object) Then
lbxTypes.Items.AddRange(CatAccessories)
End If
End Sub
|
- In the Class Name combo box, select lbxTypes
- In the Method Name combo box, select SelectedIndexChanged and implement
the event as follows:
Private Sub lbxTypes_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles lbxTypes.SelectedIndexChanged
If lbxTypes.SelectedItem = CType("Electric Guitars", Object) Then
For Each part As PartDescription In ElectricGuitars
lbxItems.Items.Add(part)
Next
ElseIf lbxTypes.SelectedItem = _
CType("Acoustic Guitars", Object) Then
For Each part As PartDescription In AcousticGuitars
lbxItems.Items.Add(part)
Next
ElseIf lbxTypes.SelectedItem = CType("Electric Bass", Object) Then
For Each part As PartDescription In ElectricBasses
lbxItems.Items.Add(part)
Next
ElseIf lbxTypes.SelectedItem = _
CType("Acoustic-Electric Bass", Object) Then
For Each part As PartDescription In AcousElectBasses
lbxItems.Items.Add(part)
Next
ElseIf lbxTypes.SelectedItem = CType("Pianos", Object) Then
For Each part As PartDescription In Pianos
lbxItems.Items.Add(part)
Next
ElseIf lbxTypes.SelectedItem = CType("Synthesizers", Object) Then
For Each part As PartDescription In Synthetizers
lbxItems.Items.Add(part)
Next
ElseIf lbxTypes.SelectedItem = CType("Books", Object) Then
For Each part As PartDescription In Books
lbxItems.Items.Add(part)
Next
ElseIf lbxTypes.SelectedItem = CType("Cables", Object) Then
For Each part As PartDescription In Cables
lbxItems.Items.Add(part)
Next
End If
End Sub
|
- Execute the application to test it
- After using the form, close it and return to your programming
environment
- In the Class Name combo box, select lbxItems
- In the Method Name combo box, select DoubleClick field and make the
following changes:
Private Sub CalculateTotalOrder()
Dim SubTotal1 As Double
Dim SubTotal2 As Double
Dim SubTotal3 As Double
Dim SubTotal4 As Double
Dim SubTotal5 As Double
Dim SubTotal6 As Double
Dim OrderTotal As Double
Try
SubTotal1 = CDbl(txtSubTotal1.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
SubTotal2 = CDbl(txtSubTotal2.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
SubTotal3 = CDbl(txtSubTotal3.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
SubTotal4 = CDbl(txtSubTotal4.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
SubTotal5 = CDbl(txtSubTotal5.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
SubTotal6 = CDbl(txtSubTotal6.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
' Calculate the total value of the sub totals
OrderTotal = SubTotal1 + SubTotal2 + SubTotal3 + _
SubTotal4 + SubTotal5 + SubTotal6
' Display the total order in the appropriate text box
txtTotalOrder.Text = OrderTotal.ToString()
End Sub
Private Sub lbxItems_DoubleClick(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles lbxItems.DoubleClick
' We will use a PartDescription object to
' identify the selected item
Dim part As PartDescription = New PartDescription()
' When the user double-clicks an item, retrieve it as
' a PartDescription object
part = CType(lbxItems.SelectedItem, PartDescription)
' If the first Part # box is empty, then use it
If txtPartID1.Text = "" Then
' Display the item number in the Part # text box
txtPartID1.Text = part.PartNumber
' Display the name of the selected item in
' the current Description text box
txtDescription1.Text = part.PartName
' Display the unit price of this item in
' the corresponding Unit Price text box
txtUnitPrice1.Text = part.UnitPrice.ToString()
' Enable the Remove button of the current item
btnRemove1.Enabled = True
' Since an item was selected, set its quantity to 1
txtQuantity1.Text = "1"
' Calculate the sub total of the current item item
txtSubTotal1.Text = (part.UnitPrice * 1).ToString()
' Give focus to the Qty text box of the current item
txtQuantity1.Focus()
' If the previous Part # text box is not empty,
' then use the next one
ElseIf txtPartID2.Text = "" Then
txtPartID2.Text = part.PartNumber
txtDescription2.Text = part.PartName
txtUnitPrice2.Text = part.UnitPrice.ToString()
' Enable the Remove button of the current item
btnRemove2.Enabled = True
txtQuantity2.Text = "1"
txtSubTotal2.Text = (part.UnitPrice * 1).ToString()
txtQuantity2.Focus()
ElseIf txtPartID3.Text = "" Then
txtPartID3.Text = part.PartNumber
txtDescription3.Text = part.PartName
txtUnitPrice3.Text = part.UnitPrice.ToString()
' Enable the Remove button of the current item
btnRemove3.Enabled = True
txtQuantity3.Text = "1"
txtSubTotal3.Text = (part.UnitPrice * 1).ToString()
txtQuantity3.Focus()
ElseIf txtPartID4.Text = "" Then
txtPartID4.Text = part.PartNumber
txtDescription4.Text = part.PartName
txtUnitPrice4.Text = part.UnitPrice.ToString()
' Enable the Remove button of the current item
btnRemove4.Enabled = True
txtQuantity4.Text = "1"
txtSubTotal4.Text = (part.UnitPrice * 1).ToString()
txtQuantity4.Focus()
ElseIf txtPartID5.Text = "" Then
txtPartID5.Text = part.PartNumber
txtDescription5.Text = part.PartName
txtUnitPrice5.Text = part.UnitPrice.ToString()
' Enable the Remove button of the current item
btnRemove5.Enabled = True
txtQuantity5.Text = "1"
txtSubTotal5.Text = (part.UnitPrice * 1).ToString()
txtQuantity5.Focus()
ElseIf txtPartID6.Text = "" Then
txtPartID6.Text = part.PartNumber
txtDescription6.Text = part.PartName
txtUnitPrice6.Text = part.UnitPrice.ToString()
' Enable the Remove button of the current item
btnRemove6.Enabled = True
txtQuantity6.Text = "1"
txtSubTotal6.Text = (part.UnitPrice * 1).ToString()
txtQuantity6.Focus()
' If all Part # text boxes are filled, don't do anything
Else
Exit Sub
End If
' Calculate the current total order and update the order
CalculateTotalOrder()
End Sub
|
- Under the above procedure, create a new procedure as follows:
Private Sub TextBoxLeaving(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles txtUnitPrice1.Leave, txtQuantity1.Leave, _
txtUnitPrice2.Leave, txtQuantity2.Leave, _
txtUnitPrice3.Leave, txtQuantity3.Leave, _
txtUnitPrice4.Leave, txtQuantity4.Leave, _
txtUnitPrice5.Leave, txtQuantity5.Leave, _
txtUnitPrice6.Leave, txtQuantity6.Leave
Dim Quantity1 As Integer, Quantity2 As Integer
Dim Quantity3 As Integer, Quantity4 As Integer
Dim Quantity5 As Integer, Quantity6 As Integer
Dim UnitPrice1 As Double, UnitPrice2 As Double
Dim UnitPrice3 As Double, UnitPrice4 As Double
Dim UnitPrice5 As Double, UnitPrice6 As Double
Dim SubTotal1 As Double, SubTotal2 As Double
Dim SubTotal3 As Double, SubTotal4 As Double
Dim SubTotal5 As Double, SubTotal6 As Double
' Get the quantity of the current item
Try
Quantity1 = CInt(txtQuantity1.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
' Get the unit price of the current item
Try
UnitPrice1 = CDbl(txtUnitPrice1.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
Quantity2 = CInt(txtQuantity2.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
UnitPrice2 = CDbl(txtUnitPrice2.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
Quantity3 = CInt(txtQuantity3.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
UnitPrice3 = CDbl(txtUnitPrice3.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
Quantity4 = CInt(txtQuantity4.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
UnitPrice4 = CDbl(txtUnitPrice4.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
Quantity5 = CInt(txtQuantity5.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
UnitPrice5 = CDbl(txtUnitPrice5.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
Quantity6 = CInt(txtQuantity6.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
Try
UnitPrice6 = CDbl(txtUnitPrice6.Text)
Catch ex As Exception
MsgBox("Invalid Value")
End Try
' Calculate the sub totals
SubTotal1 = Quantity1 * UnitPrice1
SubTotal2 = Quantity2 * UnitPrice2
SubTotal3 = Quantity3 * UnitPrice3
SubTotal4 = Quantity4 * UnitPrice4
SubTotal5 = Quantity5 * UnitPrice5
SubTotal6 = Quantity6 * UnitPrice6
' Display the sub totals in the corresponding text boxes
txtSubTotal1.Text = CStr(SubTotal1)
txtSubTotal2.Text = CStr(SubTotal2)
txtSubTotal3.Text = CStr(SubTotal3)
txtSubTotal4.Text = CStr(SubTotal4)
txtSubTotal5.Text = CStr(SubTotal5)
txtSubTotal6.Text = CStr(SubTotal6)
' Update the order
CalculateTotalOrder()
End Sub
|
- In the Class Name combo box, select btnRemove1
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub btnRemove1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnRemove1.Click
txtPartID1.Text = ""
txtDescription1.Text = ""
txtUnitPrice1.Text = "0.00"
txtQuantity1.Text = "0"
txtSubTotal1.Text = "0.00"
btnRemove1.Enabled = False
End Sub
|
- In the Class Name combo box, select btnRemove2
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub btnRemove2_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnRemove2.Click
txtPartID2.Text = ""
txtDescription2.Text = ""
txtUnitPrice2.Text = "0.00"
txtQuantity2.Text = "0"
txtSubTotal2.Text = "0.00"
btnRemove2.Enabled = False
End Sub
|
- In the Class Name combo box, select btnRemove3
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub btnRemove3_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnRemove3.Click
txtPartID3.Text = ""
txtDescription3.Text = ""
txtUnitPrice3.Text = "0.00"
txtQuantity3.Text = "0"
txtSubTotal3.Text = "0.00"
btnRemove3.Enabled = False
End Sub
|
- In the Class Name combo box, select btnRemove4
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub btnRemove4_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnRemove4.Click
txtPartID4.Text = ""
txtDescription4.Text = ""
txtUnitPrice4.Text = "0.00"
txtQuantity4.Text = "0"
txtSubTotal4.Text = "0.00"
btnRemove4.Enabled = False
End Sub
|
- In the Class Name combo box, select btnRemove5
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub btnRemove5_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnRemove5.Click
txtPartID5.Text = ""
txtDescription5.Text = ""
txtUnitPrice5.Text = "0.00"
txtQuantity5.Text = "0"
txtSubTotal5.Text = "0.00"
btnRemove5.Enabled = False
End Sub
|
- In the Class Name combo box, select btnRemove6
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub btnRemove6_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnRemove6.Click
txtPartID6.Text = ""
txtDescription6.Text = ""
txtUnitPrice6.Text = "0.00"
txtQuantity6.Text = "0"
txtSubTotal6.Text = "0.00"
btnRemove6.Enabled = False
End Sub
|
- In the Class Name combo box, select btnClose
- In the Method Name combo box, select Click and implement the event as
follows:
Private Sub btnClose_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnClose.Click
End
End Sub
|
- Execute the application to test it
Removing Items From a List Box
|
|
If you have an undesired item in a list box, you can remove
it. To To support this operation, the ObjectCollection class provides the
Remove() method. When calling it, pass the name of the item as argument.
This means that you must know the item you are trying to delete. If you call
this method, the compiler would look for the item in the list. If the item is
found, it would be deleted.
Instead of removing an item by its name or identification,
you can use its position. To do that, you can call the RemoveAt() method
and pass the zero-based index of the undesired item. If the index is valid, the
item would be deleted from the list.
To remove all items from the list, you can call the
Clear() method.
Practical Learning: Removing Items From a List Box
|
|
- Change the SelectedIndex events of the Types and the Items list boxes as
follows:
Private Sub lbxCategories_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles lbxCategories.SelectedIndexChanged
lbxTypes.Items.Clear()
lbxItems.Items.Clear()
. . . No Change
End Sub
Private Sub lbxTypes_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles lbxTypes.SelectedIndexChanged
lbxItems.Items.Clear()
If lbxTypes.SelectedItem = CType("Electric Guitars", Object) Then
For Each part As PartDescription In ElectricGuitars
lbxItems.Items.Add(part)
Next
. . . No Change
End Sub
|
- Execute the application to test it. Here is an example:
- Close the form and return to your programming environment
After creating the list, by default, each item assumes the
position it received when it was added. If you want, you can rearrange them in
ascending order. To do this, set the ListBox.Sorted Boolean property to
True. If you create an unsorted list, then at one time get it sorted (for
example, you can give the user the ability to sort the list, by clicking a
button), the list would be sorted. If an item is added to the sorted list, the
compiler would automatically insert it to the right position following the
alphabetical, ascending or chronological order. If at another time you allow the
user to “unsort” the list, the list would keep its current order. If another
item is added when the list is not sorted, the item would be positioned at the
end of the list. If you want the list to have its original state, you would have
to reset it through code.
Practical Learning: Sorting a List Box
|
|
- On the form, click the Items list box
- In the Properties window, double-click Sorted to set its value to True
Characteristics of a List Box
|
|
If you provide a longer list than the list box' height can
display, it would have a vertical scroll bar. Here is an example:
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class Starter
Inherits Form
Private lbxFamily As ListBox
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
lbxFamily = New ListBox()
lbxFamily.Location = New Point(12, 12)
lbxFamily.Items.Add("Son")
lbxFamily.Items.Add("Daughter")
lbxFamily.Items.Add("Father")
lbxFamily.Items.Add("Mother")
Dim strMembers As String() = _
{ _
"Niece", "Nephew", "Uncle", "Aunt", _
"Grand Father", "Grand Mother" _
}
lbxFamily.Items.AddRange(strMembers)
Controls.Add(lbxFamily)
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
This would produce:
At design time, if just one or a few items are hidden by the
scroll bar, you can heighten it if the form provides more space.
Consider the following example:
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class Starter
Inherits Form
Private lbxBook As ListBox
Private lblTitle As Label
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
lblTitle = New Label()
lblTitle.Text = "Book Titles"
lblTitle.Location = New Point(12, 12)
lbxBook = New ListBox()
lbxBook.Location = New Point(12, 36)
lbxBook.Items.Add("College Algebra")
lbxBook.Items.Add("Finite Mathematics")
lbxBook.Items.Add("Mathematical Structures")
lbxBook.Items.Add("MCAD 70-316 Training Guide")
lbxBook.Items.Add("C++ Builder 6 Developer's Guide")
Controls.Add(lblTitle)
Controls.Add(lbxBook)
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
This would produce:
If at least one of the items of the list box is wider than
the width of the control, the right side(s) of that (those) may disappear. To
allow the user to see the hidden part of the item(s), you should display a
horizontal scroll bar. To support this, the ListBox class is equipped
with a Boolean property named HorizontalScrollbar. To make a list box
display a horizontal scroll bar, at design time, access the Properties window
for the list box and set its HorizontalScrollbar property to True. You can also
do this programmatically. Here is an example:
Public Sub InitializeComponent()
lblTitle = New Label()
lblTitle.Text = "Book Titles"
lblTitle.Location = New Point(12, 12)
lbxBook = New ListBox()
lbxBook.Location = New Point(12, 36)
lbxBook.Items.Add("College Algebra")
lbxBook.Items.Add("Finite Mathematics")
lbxBook.Items.Add("Mathematical Structures")
lbxBook.Items.Add("MCAD 70-316 Training Guide")
lbxBook.Items.Add("C++ Builder 6 Developer's Guide")
lbxBook.HorizontalScrollbar = True
Controls.Add(lblTitle)
Controls.Add(lbxBook)
End Sub
This property allows the operating system to find the widest
item in the list and provide a horizontal scroll bar that is long enough to
display each item when the user scrolls to the right. The above code would
produce:
If the list of items requires it, the list box would display
both the vertical and the horizontal scroll bars. Here is an example:
Public Sub InitializeComponent()
lblTitle = New Label()
lblTitle.Text = "Book Titles"
lblTitle.Location = New Point(12, 12)
lbxBook = New ListBox()
lbxBook.Location = New Point(12, 36)
lbxBook.Items.Add("College Algebra")
lbxBook.Items.Add("Finite Mathematics")
lbxBook.Items.Add("Mathematical Structures")
lbxBook.Items.Add("MCAD 70-316 Training Guide")
lbxBook.Items.Add("C++ Builder 6 Developer's Guide")
lbxBook.Items.Add("La Bible de Jérusalem")
lbxBook.Items.Add("Patterns for a Purpose")
lbxBook.HorizontalScrollbar = True
Controls.Add(lblTitle)
Controls.Add(lbxBook)
End Sub
This would produce:
If you prefer to decide how much width should be allowed,
then set the desired value in the HorizontalExtent property.
Practical Learning: Implementing List Boxes
|
|
- Display the form and click the most right list box. Using the Properties
window, set its HorizontalScrollbar property to True
- Execute the application and process an order
- After using it, close the form and return to your programming
environment
When you create a list of items, they appear in one column.
If the number of items exceeds the height, a scrollbar would appear on the
control. An alternative you can use is to span the list to more than one column.
To support this, the ListBox class is equipped with the MultiColumn
Boolean property. At design time, you can set this characteristic in the
Properties window. By default, the MultiColumn value is set to False,
which means the items appear in one column. If you set this property to True,
then the compiler would decide if or when the control needs the columns, based
on the number of items in the list. You can then specify the width of each
column using the ColumnWidth property.
A Custom Owner-Draw List Box
|
|
A list box is painted based on three types or style. This
characteristic is controlled by the DrawMode property. When its value is
set to Normal, the operating system would regularly draw each item of the
list. If you want each item of the list to display a graphic or a color, you
must set the style to an owner drawn type. The OwnerDrawFixed value
allows you to set a desired but same height for each item of the list. This
height is controlled through the ItemHeight property. You can set a
different height for each item if you set the list style to OwnerDrawVariable.
Download
|
|