Chapter Seven Lists and Combo Boxes
Chapter Seven Lists and Combo Boxes
Coverage:
This chapter teaches you to use ListBox and ComboBox controls in designing forms.
Additionally, you will learn to code loop structures, both condition-controlled (Do loops) and
count-controlled loops (For...Next loops).
Outline:
INTRODUCTION
Chapter 7 In-Class Project
In this chapter you will develop a project for the VB University that can be used for data entry of
employee information. The form will make use of a new type of control – a list control. This
form includes both a ListBox and two ComboBox controls. List type controls allow an
application user to select from a list of items and to display a list of items.
This figure (a VB project form) displays different styles for these controls.
ListBox – size the control as desired; application user selects from the list – new items
cannot be typed into the list.
ComboBox – has a DropDownStyle property that affects how the control works.
o DropDownStyle = Simple – you can type text into the TextBox at the top of the
ComboBox control – the list displays in a ListBox format and then you can scroll
up and down the listing.
1. As you type a letter, the control automatically searches for the first item in
the listing that begins with that letter.
2. The listing drops down when you click the drop-down arrow.
3. The background color of the control with this setting is gray to indicate that
you cannot add new items.
Automatically have a vertical scroll bar added by VB when the list is too large to
display all items on the form.
Have a Sorted property that will automatically sort the list when set to True.
ListBox controls display the Name property at design time – you cannot delete it, but the name
does not appear at run time. Also, if items are added to the control the name property
disappears at design time.
ComboBox controls display the Text property. At run time they display the appropriate values
so don't worry about what they display at design time.
The Items collection has properties and methods to make it easy to add items, remove
items, and refer to individual items.
The items in the list are numbered beginning with the number 0. A list of 10 items has
the items numbered 0 through 9.
1. If the list of items varies, the best way to fill a list is to store values into the list control's Items
collection from a database table
2. If the list of items never changes or does not change much, you can add items at design type by
clicking on the Items property shown in this figure – a String Collection Editor window will
open and you type the items into the editor window.
In-Class Exercise
Property settings for the controls:
TitleComboBox:
o DropDownStyle – DropDownList
Professor
Associate Professor
Assistant Professor
Lecturer
DepartmentComboBox:
o DropDownStyle - DropDown
Accounting
Economics & Finance
CMIS
EmployeeListBox:
The form has a menu strip control with the following menu entries.
Run the project – test that the ComboBox controls have appropriate lists as specified by you at
design time.
Coding ListBox and ComboBox Controls
Items.Add Method
The Items.Add method is used to add an item to a list or ComboBox at run time.
Example commands to add a new faculty listing to the EmployeeListBox and new departments
to the DepartmentComboBox controls are shown below:
EmployeeListBox.Items.Add("Mary Sumner")
EmployeeListBox.Items.Add(EmployeeNameTextBox.Text)
EmployeeListBox.Items.Add(NewEmployeeNameString )
DepartmentComboBox.Items.Add("Chemistry")
DepartmentComboBox.Items.Add(DepartmentComboBox.Text)
DepartmentComboBox.Items.Add(NewDepartmentNameString)
In-Class Exercise
Task #1: Code the Click event sub procedure for the Add Department menu item.
Add the value typed into the DepartmentComboBox control's Text property to the
Items collection of the ComboBox control.
Check to ensure that the Text property is not the empty string.
'Ok to add
DepartmentComboBox.Items.Add(DepartmentComboBox.Text)
Else
'Cannot add
DepartmentComboBox.Focus()
End If
End Sub
In the above coding segment, if the Text property is not the empty string, the Text property
value is added to the Items collection. The code does not handle the insertion of duplicate
department name items.
Task #2: Code the Click event sub procedure for the Add Employee menu item.
EmployeeListBox.Items.Add(NewEmployeeString)
EmployeeNameTextBox.Clear()
TitleComboBox.SelectedIndex = -1
DepartmentComboBox.SelectedIndex = -1
SalaryTextBox.Clear()
'Set focus
EmployeeNameTextBox.Focus()
End Sub
Items.Insert Method
If a list is unsorted, you can use the Items.Insert method to specify exactly where within an
Items collection to add a new item. You do this by specifying the number position in the
collection – this is also called the index position of the new item.
This coding statement adds the item Chemistry as the very first item in the
DepartmentComboBox control; however, if the Sorted property is True, then specifying the
location will not have any effect.
DepartmentComboBox.Items.Insert(0, "Chemistry")
If the ListBox or ComboBox control is sorted, then the Insert method appears to work exactly
as the Add method – the new item is added at the location specified, but then control then
immediately resorts the listing.
Items.Clear Method
The Items.Clear method will remove the contents of a ListBox or ComboBox.
DepartmentComboBox.Items.Clear()
In-Class Exercise
Task: Code the Click event sub procedure for the Clear Employee List menu item.
Declare a dialog result variable and display a message box that asks the system user if
they want to "Clear employee listing?" – capture their response to the variable.
The message box will display Yes and No buttons – make No the default button with the
MessageBoxDefaultButton.Button2 parameter.
If ResponseDialogResult = Windows.Forms.DialogResult.Yes
Then
EmployeeListBox.Items.Clear()
End If
End Sub
Run the project, add two faculty members, then test the ability to clear the listing.
SelectedIndex and SelectedItem Properties
When you select an item from a list, the index number associated with the item is stored to the
SelectedIndex property.
You can select (highlight) an item in a list by storing a numeric value to the
SelectedIndex property.
DepartmentComboBox.SelectedIndex = 3
DepartmentComboBox.SelectedIndex = -1
When you select an item from a list, the selected item is stored to the SelectedItem property.
This property can be used to display the selection elsewhere, for example, in a message box or to
a TextBox control.
MessageBox.Show(EmployeeListBox.SelectedItem.ToString)
The ToString method ensures the item (that is stored in the list as an object) converts to
string for storage to the Text property of the TextBox control.
The ToString method is optional, but MUST be used if Option Strict On is set.
EmployeeInformationTextBox.Text = EmployeeListBox.Items(0).ToString()
The Reset Employee menu item Click event sub procedure demonstrates setting the
SelectedIndex property to -1 to unselect items in two ComboBox controls and one ListBox
control.
EmployeeNameTextBox.Clear()
SalaryTextBox.Clear()
TitleComboBox.SelectedIndex = -1
DepartmentComboBox.SelectedIndex = -1
TitleComboBox.Text = String.Empty
DepartmentComboBox.Text = String.Empty
EmployeeListBox.SelectedIndex = -1
EmployeeNameTextBox.Focus()
End Sub
In-Class Exercise
Task #1: Code the Click event sub procedure for the Display Selected Faculty menu item.
Use a message box to display the current selected item from the EmployeeListBox
control.
Private Sub DisplaySelectedToolStripMenuItem_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles
DisplaySelectedToolStripMenuItem.Click
If EmployeeListBox.SelectedIndex = -1 Then
Else
MessageBox.Show(EmployeeListBox.SelectedItem.ToString, "Current
selection", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Task #2: Code the Click event sub procedure for the Reset Employee menu item as shown
earlier.
Items.Count Property
The Items.Count property stores a number equal to the number of items in a list or ComboBox
Items collection.
The value of Items.Count is always 1 more than the maximum allowable SelectedIndex
value.
If there are 5 items in a list, then SelectedIndex possible values are 0 through 4, but
Items.Count equals 5.
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
The RemoveAt method fails if an item has not been selected for removal because the value of
SelectedIndex = -1 and you cannot remove a non-existent item – this throws an exception:
ArgumentOutOfRangeException.
When the Remove method is used and an item has not been selected for removal, the method
simply does nothing.
DepartmentComboBox.Items.RemoveAt(0)
DepartmentComboBox.Items.RemoveAt(IndexInteger)
DepartmentComboBox.Items.RemoveAt(DepartmentComboBox.SelectedIn
dex)
DepartmentComboBox.Items.Remove(DepartmentComboBox.SelectedItem
)
In-Class Exercise
Task #1: Code the Click event sub procedure for the Department menu, Count Departments
menu item.
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Task #2: Code the Click event sub procedure for the Department menu, Remove Department
menu item.
as shown here.
If ResponseDialogResult = Windows.Forms.DialogResult.Yes
Then
DepartmentComboBox.Items.Remove(DepartmentComboBox.SelectedItem)
'item in a list.
DepartmentComboBox.Text = String.Empty
End If
End Sub
Task #3: Code for the Click event sub procedure for the Department menu, Remove At
Department menu item.
Try
If ResponseDialogResult =
Windows.Forms.DialogResult.Yes Then
DepartmentComboBox.Items.RemoveAt(DepartmentComboBox.SelectedInde
x)
'item in a list.
DepartmentComboBox.Text = String.Empty
End If
Catch ex As ArgumentOutOfRangeException
End Try
End Sub
SelectedIndexChanged Event. Occurs when a system user makes a new selection for a
list or ComboBox.
TextChanged Event. As a system user types characters into the TextBox portion of a
ComboBox, this event is triggered for each character typed. ListBoxes do not have this
event.
Enter Event. When a list or ComboBox receives focus, this event occurs.
Leave Event. When a list or ComboBox loses focus, this event occurs.
In-Class Exercise
Task: Code the Leave event.
Next select the Leave event from the Declarations (property, method and event) drop-
down ComboBox.
Code the Leave event to add the value that is typed into the Text property of
DepartmentComboBox to the Items collection of DepartmentComboBox.
DepartmentComboBox.Items.Add(DepartmentComboBox.Text)
End Sub
Note that this code enables adding duplicate values as well as blank values.
Loops
Loop structures enable you to execute a series of VB statements over and over. A loop iteration
is a single execution of the loop.
Condition-controlled. In VB, these are Do Loops – loops that execute over and over
until a specific condition occurs. In VB.NET, these are Do Loops.
Count-controlled. In VB, these are For…Next Loops – loops that execute for a
specified number of times.
Do Loops
Do Loops can execute the coding statements within the body of the loop either:
Until a condition is met that causes the loop to terminate (stop executing),
Do Loops can have the condition test (termed the stopping condition) at either the top or
bottom of a loop, and can use either a While or Until option to test the condition.
Condition at Top of Loop – While Logic. The following loop executes while the stopping
condition FoundBoolean is False.
FoundBoolean = True
Else
IndexInteger += 1
End If
Loop
FoundBoolean = True
Else
IndexInteger += 1
End If
Loop
Condition at Bottom of Loop – While Logic. This next loop will always execute the body of
the loop at least one time because the stopping condition is not tested until the end of the loop.
Do
FoundBoolean = True
Else
IndexInteger += 1
End If
Loop While FoundBoolean = False
You can also test for an Until condition at the bottom of a Do Loop.
Start the search with the first department in the ComboBox by setting IndexInteger = 0.
Use a Do Loop to examine each department in the Items collection starting at item 0
until there are no more items.
o If a department in the collection matches the Text property value, then set
FoundBoolean = True and stop the search.
o If no department matches the Text property value, the item index variable
IndexInteger will eventually grow in value until it equals
DepartmentComboBox.Count – in this situation, you can add the department to the
ComboBox Items Collection property.
o Note the use of multiple methods ToString, Trim, and ToUpper with the
DepartmentComboBox to convert the value to a string, trim off any leading/trailing
blank spaces, and treat the value as if it were entered in all capital letters.
If DepartmentComboBox.Text.Trim.ToUpper =
DepartmentComboBox.Items(IndexInteger).ToString.Trim.ToUpper Then
FoundBoolean = True
Else
IndexInteger += 1
End If
DepartmentComboBox.Items.Add(DepartmentComboBox.Text.Trim)
Else
DepartmentComboBox.Focus()
DepartmentComboBox.SelectAll()
End If
End Sub
In-Class Exercise
Replace the code for the Add Department menu item's click event with the code shown above.
Run the project and test the system by adding a new department (Philosophy), a duplicate
department (Accounting), and a blank department value.
For…Next Loops
A For…Next loop is a count-controlled loop – the code executes a set number of times based
on a loop index.
The loop index is initialized to a starting value. The starting value in the code below is 1.
After each execution of the loop, the loop index is changed (made larger or smaller) by the step
value. The step value in the example below is 2. The Step value is optional - if it is not
specified, it is automatically assumed to be 1.
The loop terminates when the loop index exceeds the ending value. The ending value below is
5.
CountListBox.Items.Add(IndexInteger.ToString)
Next IndexInteger
MessageBox.Show("Finished Counting")
End Sub
In-Class Exercise
Task 1. Counting Forward
Add a ListBox to the form named CountListBox, and a menu item under the File menu
named Count.
Add the code to the Count menu item's Click event shown in the above example.
Try different values for the ending value and step increment.
Modify the code for the File-Count menu to count backwards from 10 to 1 by 1. The solution
given here stops when IndexInteger is less than 1.
CountListBox.Items.Add(IndexInteger.ToString)
Next IndexInteger
Task 3. Computing Interest
Write code for the File-Compute Interest menu option that will compute compound interest on an initial
investment of $1,000 at 6% for a 5-year period and display the balance at the end of the period by using a
message box.
'interest on an investment
Next Index
End Sub
Next IndexInteger
An Endless Loop
This loop executes endlessly because IndexInteger is reset to the starting value every time the
loop executes.
For IndexInteger = 1 To 5
IndexInteger = 1
Next IndexInteger
Once a For...Next loop begins to execute, the values of starting value, ending value, and step
increment are set – changing these values within the loop CAN affect execution of the loop.
For OuterIndexInteger = 1 To 10
'Start of the inner loop – each time we get here the
For InnerIndexInteger = 1 To 10
TotalLong += 1
CountListBox.Items.Add(TotalLong.ToString)
Next InnerIndexInteger
Next OuterIndexInteger
Exit Statement
The Exit For statement is used to exit a For...Next loop before the ending value is reached.
Example:
For IndexInteger = 1 To 10
MessageBox.Show("Input is invalid")
Exit For
End If
Next IndexInteger
There are also Exit Do and Exit While and Exit If statements. For the most part, using any Exit
statement is unnecessary if your code is constructed properly.
EmployeeNameTextBox.SelectAll()
End Sub
EmployeeListBox.SelectedIndex = IndexInteger
This sub procedure shows code for the TextChanged event for the FruitTextBox control –
whenever a character is typed into the TextBox, it triggers a search for a matching value in the
FruitListBox.
Private Sub FruitTextBox_TextChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
FruitTextBox.TextChanged
ListItemString =
FruitListBox.Items(IndexInteger).ToString.ToUpper
If
ListItemString.StartsWith(FruitTextBox.Text.ToUpper) Then
FruitListBox.SelectedIndex = IndexInteger
FoundBoolean = True
Else
IndexInteger += 1
End If
Loop
End If
End Sub
In-Class Exercise
Task #1: Selecting a TextBox Entry
Add a TextBox control named FruitTextBox and a ListBox control named FruitListBox
to the form.
Add some fruit items to the Items collection for the fruit ListBox.
Use the SelectAll method as shown earlier to test your ability to highlight text in the fruit
ListBox control.
Type a value in the TextBox, then tab around the form until the TextBox is again selected
– it should highlight the text in the control.
FruitTextBox.SelectAll()
End Sub
Use the code shown above to search for a value in the FruitListBox as you type the
name of a type of fruit into the FruitTextBox.
'D. Bock
'Today's Date
Option Strict On
If DepartmentComboBox.Text.Trim.ToUpper =
DepartmentComboBox.Items(IndexInteger).ToString.Trim.ToUpper Then
FoundBoolean = True
Else
IndexInteger += 1
End If
Else
DepartmentComboBox.Focus()
DepartmentComboBox.SelectAll()
End If
End Sub
If ValidData Then
EmployeeListBox.Items.Add(NewEmployeeString)
EmployeeNameTextBox.Clear()
TitleComboBox.SelectedIndex = -1
DepartmentComboBox.SelectedIndex = -1
DepartmentComboBox.Text = String.Empty
SalaryTextBox.Clear()
'Set focus
EmployeeNameTextBox.Focus()
End If
End Sub
If ResponseDialogResult = Windows.Forms.DialogResult.Yes
Then
EmployeeListBox.Items.Clear()
End If
End Sub
EmployeeNameTextBox.Clear()
SalaryTextBox.Clear()
TitleComboBox.SelectedIndex = -1
DepartmentComboBox.SelectedIndex = -1
TitleComboBox.Text = String.Empty
DepartmentComboBox.Text = String.Empty
EmployeeListBox.SelectedIndex = -1
EmployeeNameTextBox.Focus()
End Sub
If EmployeeListBox.SelectedIndex = -1 Then
MessageBox.Show("You must select an employee member
to display.", "No Selection Error", MessageBoxButtons.OK,
MessageBoxIcon.Error)
Else
MessageBox.Show(EmployeeListBox.SelectedItem.ToString, "Current
selection", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
DepartmentComboBox.Items.Remove(DepartmentComboBox.SelectedItem)
'item in a list.
DepartmentComboBox.Text = String.Empty
End If
End Sub
Try
If ResponseDialogResult =
Windows.Forms.DialogResult.Yes Then
DepartmentComboBox.Items.RemoveAt(DepartmentComboBox.SelectedInde
x)
'This next line of code clears the Text
'item in a list.
DepartmentComboBox.Text = String.Empty
End If
Catch ex As ArgumentOutOfRangeException
End Try
End Sub
For OuterIndexInteger = 1 To 3
For InnerIndexInteger = 1 To 6
TotalLong += 1
CountListBox.Items.Add(TotalLong.ToString)
Next InnerIndexInteger
Next OuterIndexInteger
MessageBox.Show("Finished Counting.")
End Sub
ListItemString =
FruitListBox.Items(IndexInteger).ToString.ToUpper
If
ListItemString.StartsWith(FruitTextBox.Text.ToUpper) Then
FoundBoolean = True
Else
IndexInteger += 1
End If
Loop
End If
End Sub
End Sub
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Private Function ValidData() As Boolean
ValidData = False
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
EmployeeNameTextBox.Focus()
EmployeeNameTextBox.SelectAll()
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
TitleComboBox.Focus()
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
DepartmentComboBox.Focus()
MessageBox.Show(MessageString, TitleString,
MessageBoxButtons.OK, MessageBoxIcon.Error)
SalaryTextBox.Focus()
SalaryTextBox.SelectAll()
Else
ValidData = True
End If
End Function
Next Index
End Sub
End Class
End of Notes