Amazing things you can do with the Listbox control

Level:
Level3

We encounter lists all the time in our every day lives. From grocery stores, task todo lists, to lists of people in a classroom or office. Because of this both Visual Basic 6 and VBA provide us with great listbox control. This tutorial focuses primary on VB6, but the VBA listbox has very similar functionality.

ListBoxes provide two property arrays into which you can place data: List and ItemData. Whenever you reference these properties of the ListBox control, you must do so with an index reference, i.e.:

 

List1.List(X) or List1.ItemData(X)

 

The List array is a zero-based array of STRING items and is what the user sees in the ListBox. The ItemData array is an array of LONG INTEGER items in which you can OPTIONALLY place a numeric data item associated with the corresponding string item. If ItemData is used, each element is always associated with the corresponding element of the List array; it is not an independent array.

 

You cannot tell VB ahead of time how many items will be placed in the ListBox. The number of elements in the ListBox is maintained by VB via the ListCount property (a read-only property of ListBoxes), which is dependent on the use of the AddItem method to get items into the ListBox and the RemoveItem method to get items out of the ListBox.

 

Getting Data into a ListBox

 

The AddItem Method

 

To get data into the ListBox, you use the AddItem method. The syntax is:

 

ListboxName.AddItem string

 

This syntax places the string item into an element of the List property array. It does not affect the ItemData property array; the AddItem method is not used to place data in the ItemData array. The technique to place an item into the corresponding element of the ItemData array will be shown a little further below. Remember that the use of the ItemData array is optional, and if your application does not need to have numeric items associated with the string items in the ListBox, then you need not use it.

 

With the AddItem method, the issue of which element of the List array an item is placed in depends on the setting of the Sorted property. You can set the Sorted property of the ListBox control at design time to True or False; by default it is set to False.

 

When Sorted is False, VB adds items to the ListBox in sequential order. For example, consider the following three statements to add the items "Orange", "Apple", and "Banana" to a ListBox called lstFood:

 

lstFood.AddItem "Orange"

lstFood.AddItem "Apple"

lstFood.AddItem "Banana"

 

The data would be stored in the ListBox in the following manner:

 

Array Index #

List Array Elements

0

Orange

1

Apple

2

Banana


When Sorted is True, VB automatically adjusts the indexes as items are added to the ListBox so that the elements of the List array are in ascending sequence. Once again, assume you coded the following:

 

lstFood.AddItem "Orange"

lstFood.AddItem "Apple"

lstFood.AddItem "Banana"

 

The data would be stored in the ListBox in the following manner:

 

Array Index #

List Array Elements

0

Apple

1

Banana

2

Orange

 

Now suppose we wanted to store the number of calories for each food in the ListBox. You could use the ItemData property of the ListBox to store the number 105 for "Banana", 60 for "Orange", and 80 for "Apple".

 

To place items in the ItemData property array of the ListBox, you can use the (read-only) NewIndex property of the ListBox control, which represents the index of last item added to the ListBox with the AddItem method. Using the earlier example with the Sorted property set to False, the statement

 

lstFood.AddItem "Orange"

 

would cause the NewIndex property to be set to zero (0) – because "Orange" was the first item added to the list, and the indexes start with zero. Therefore, the following statement would place the number 60 in the corresponding element (0) of the ItemData array:

 

lstFood.ItemData(lstFood.NewIndex) = 60

 

Expanding the earlier example, suppose we had these statements following the two above:

 

lstFood.AddItem "Apple"

 

NewIndex is now 1

 

lstFood.ItemData(lstFood.NewIndex) = 80

lstFood.AddItem "Banana"

 

NewIndex is now 2

 

lstFood.ItemData(lstFood.NewIndex) = 105

 

The data would be stored in the ListBox in the following manner:

 

Array Index #

List Array Contents

ItemData Array Contents

0

Orange

60

1

Apple

80

2

Banana

105

 

If the Sorted property were set to True, the sequence of events would be as follows:

 

lstFood.AddItem "Orange"

 

NewIndex is now 0

 

lstFood.ItemData(lstFood.NewIndex) = 60

lstFood.AddItem "Apple"

 

NewIndex is now 0 – (The "Orange" item (and its ItemData of 60) is moved to index #1)

 

lstFood.ItemData(lstFood.NewIndex) = 80

lstFood.AddItem "Banana"

 

NewIndex is now 1 – ("Apple" remains at index #0, and "Orange" is moved to index #2)

 

lstFood.ItemData(lstFood.NewIndex) = 105

 

 

The data would be stored in the ListBox in the following manner:

 

Array Index #

List Array Contents

ItemData Array Contents

0

Apple

80

1

Banana

105

2

Orange

60

 

 

Coding Tip:

 

Note in the statements above the frequent references to the name of the ListBox control, "lstFood". When you use the same object reference (lstFood in this case) in a group of statements, you can enclose those statements in a With/End With block to "factor out" the object name. For example, the six statements in our example could be rewritten as follows:

 

With lstFood

.AddItem "Orange"

.ItemData(.NewIndex) = 60

.AddItem "Apple"

.ItemData(.NewIndex) = 80

.AddItem "Banana"

.ItemData(.NewIndex) = 105

End With

 

The AddItem examples we looked at thus far used literal values to load the ListBox. Often, you'll want to load a listbox with data from a file or database table. For example, suppose we had a sequential file called "FOOD.DAT" which contained the following records:

 

"Orange",60

"Apple",80

"Banana",105

 

To load this data into the ListBox, you could use the following code:

 

Dim strFood As String

Dim intCalCount As Integer

 

Open "FOOD.DAT" For Input As #1

Do Until EOF(1)

Input #1, strFood, intCalCount

With lstFood

.AddItem strFood

.ItemData(.NewIndex) = intCalCount

End With

Loop

Close #1

 

 

Placing Items in a ListBox at Design Time

 

At design time, you can access the property sheet for the ListBox and add items via the List property, as shown in the screen-shot below. To add multiple items to the list, you press Ctrl-Enter to move to the next line in the list (just pressing Enter will close the property). You can also add to the ItemData property in this manner (however, you must specify items for List before specifying items for ItemData). Placing items in the list this way eliminates the need to use the AddItem method. You would typically add items to this list in this manner if the list is to remain static (i.e., the items are not expected to change).

 


Referencing Data Items Stored in a ListBox

 

As mentioned in the beginning of this document, you can reference any element of the List property array or ItemData property array (regardless of whether or not that item is selected) with a valid index reference, i.e.:

 

ListboxName.List(IndexValue)

ListboxName.ItemData(IndexValue)

 

A valid index reference is an integer between zero and one less than the number of items stored in the ListBox. For example, if there are 5 items in theListBox, a valid index reference is a number between 0 and 4. To determine the number of items stored in the ListBox, you use the ListCount property of the ListBox. For example, the following code prints the contents of the List and ItemData arrays on the background area of the form:

 

Dim intX As Integer

With lstFood

For intX = 0 To .ListCount – 1

Print .List(intX), .ItemData(intX)

Next

End With

 

Determining Which Items in a ListBox Are Selected

 

Typically, you only care about what items in the listbox were selected by the user. The issue of whether or not the user is permitted to select multiple items from the ListBox then comes up. You determine this at design-time by setting the MultiSelect property in the property sheet of the ListBox.

 

By default, the MultiSelect property is set to "0 – None", meaning that only one item can be selected from the ListBox. If the user selects one item, then clicks a different item, the item previously selected is de-selected. If you want to allow the user to select more than one item from the ListBox, you can set the MultiSelect property to either "1 – Simple", or "2 – Extended". "Simple" allows the user to select more than one item by first clicking an item, then Ctrl-clicking subsequent items. "Extended" does the same thing as "Simple", but also supports selecting a group of contiguous items by allowing the user to click the first item in the group and then Shift-click the last item in the group.

 

If MultiSelect is set to None:

 

When you are only allowing the user to select one item from the list, there are two ways to determine which item is selected. One way involves the Text property of the ListBox, the other way involves the ListIndex property of the ListBox. Suppose you have a ListBox and a command button on your form. When the user clicks the command button, you want to process the item that the user has selected from the ListBox. As an example, to store the user's selection in a string variable called strListSel, you could place this code behind the command button:

 

strListSel = lstFood.Text

 

The Text property of the ListBox stores the contents of the List array item that is selected.

 

Alternatively, you can use the ListIndex property to access the contents of the List item that is selected. The ListIndex property is an integer value representing the index of the currently selected item. Therefore, the following statement achieves the same result as the one above:

 

strListSel = lstFood.List(lstFood.ListIndex)

 

To access the contents of the ItemData element corresponding to the item in the list that is selected, you must use the ListIndex property. Suppose you wanted to store the ItemData contents corresponding to the user's selection in a long variable called lngCalCount. You could place this code behind the command button:

 

lngCalCount = lstFood.ItemData(lstFood.ListIndex)

 

 

Pre-Selecting an Item in a ListBox:

 

If you load a ListBox but do not pre-select an item from the list in code, then by default, the value of ListIndex will be 0. When ListBox is first displayed on the form, the first item in the list will show the focus rectangle, but will not be highlighted. To pre-select an item in code (so that the user is presented with a default selection), use the following:

 

lstFood.ListIndex = 0

 

The above code highlights and pre-selects the first item in the ListBox. You could set the ListIndex to any other valid index number.

 

If you wish to NOT pre-select an item from the ListBox (and sometimes this will be the case, because you do not want to default a selection for the user), you can set the ListIndex property to –1. A value of –1 for ListIndex indicates that no item is selected:

 

lstFood.ListIndex = -1

 

If you do the above, you must be careful about subsequent references to ListIndex, because if the user never selects an item from the ListBox, ListIndex will remain at –1 and therefore would not refer to a valid element of the List or ItemData arrays, and statements like the ones we looked at earlier would cause a run-time error:

These statements would cause run-time errors if ListIndex = -1:

 

strListSel = lstFood.List(lstFood.ListIndex)

lngCalCount = lstFood.ItemData(lstFood.ListIndex)

 

You could avoid this problem by testing ListIndex for a value of -1:

If lstFood.ListIndex <> -1 Then

strListSel = lstFood.List(lstFood.ListIndex)

lngCalCount = lstFood.ItemData(lstFood.ListIndex)

End If

 

 

If MultiSelect is set to Simple or Extended:

 

If the MultiSelect property of the ListBox is set to a "non-None" value (i.e., either "Simple" or "Extended"), you use the Selected property array of the ListBox in a loop to determine the selected items. Like List and ItemData, Selected is a property array of the ListBox. Each element of Selected stores a Boolean value of True or False, indicating whether or not the corresponding List item is selected. In code, the Selected property is referenced as follows:

 

ListboxName.Selected(IndexValue)

 

The following code loops through the items in the lstFood ListBox and prints each selected item, along with its ItemData property, on the background area of the form:

 

Dim intX As Integer

With lstFood

For intX = 0 To .ListCount – 1

If .Selected(intX) Then

Print .List(intX), .ItemData(intX)

End If

Next

End With

 

 

Pre-Selecting an Item in a ListBox with the Selected Property:

 

Previously, you learned that you can pre-select an item in a ListBox with the ListIndex property. An alternative way of pre-selecting an item in a ListBox is to use the Selected property. For example, the following statement pre-selects the first item in the lstFood ListBox:

 

lstFood.Selected(0) = True

 

 

 

Removing Items from a ListBox

 

To remove ALL items from a ListBox, you use the Clear method. The syntax is simply:

 

ListboxName.Clear

 

More frequently, you'll only want to remove a particular item or items from the ListBox, in which case you use the RemoveItem method. The RemoveItem method requires you to specify the index value of the element you want to remove:

 

ListboxName.RemoveItem IndexValue

 

For example, the following code removes the second item from the lstFood ListBox:

 

lstFood.RemoveItem 1

 

In applications where you have a ListBox from which you will allow users to remove items, you will want to remove the selected item. To do so, use the ListIndex property, as in the following example:

 

lstFood.RemoveItem lstFood.ListIndex

 

Now the issue of how to remove multiple items from a ListBox comes up. If you have a ListBox from which you will allow users to remove items, and you are allowing multiple selection, you must loop through the listbox in REVERSE: i.e., start the loop index at ListCount – 1 and end the loop index at zero.

 

The following code will remove the items that the user has selected from the lstFood listbox:

 

Dim intListX As Integer

 

For intListX = (lstFood.ListCount – 1) To 0 Step -1

If lstFood.Selected(intListX) Then

lstFood.RemoveItem intListX

End If

Next

 

Example: Adding and Removing Items with Two ListBoxes

 

A commonly seen action in Windows programs is one in which you have two ListBoxes, where one ListBox contains all of the available items; the other is intended to contain selected items from the list of all available items. The user adds and removes items by selecting items from the ListBoxes and then clicking an appropriate command button. Consider the following interface:

 

 

The above interface consists of two ListBoxes, named lstAvail and lstSelected. Both have their Sorted property set to True and their MultiSelect property set to Extended. The two command buttons are named cmdAdd and cmdRemove. To move the selected items from lstAvail to lstSelected, place the following code in the cmdAdd_Click event:

 

Private Sub cmdAdd_Click()

 

Dim intListX As Integer

For intListX = lstAvail.ListCount – 1 To 0 Step -1

If lstAvail.Selected(intListX) Then

lstSelected.AddItem lstAvail.List(intListX)

' If you are using the optional ItemData property array,

' add the following line to carry the "ItemData baggage" along ...

lstSelected.ItemData(lstSelected.NewIndex) = _

lstAvail.ItemData(intListX)

lstAvail.RemoveItem intListX

End If

Next

 

End Sub

 

As indicated by the comment in the above code, if you are using the optional ItemData property array, this ItemData "baggage" is not carried along automatically when you move an item from one list to another with the AddItem method. If you were to omit the line

 

lstSelected.ItemData(lstSelected.NewIndex) = lstAvail.ItemData(intListX)

 

the ItemData data would be deleted with the RemoveItem method.

 

After execution of the above code, the form will look like this:

 

Note that the selected items were added to lstSelected and removed from lstAvail.

 

Now suppose the user wants to remove a few items from lstSelected and send them back to lstAvail. The user selects the items to remove:

 

 

The user then clicks the Remove button, which contains the following code:

 

Private Sub cmdRemove_Click()

Dim intListX As Integer

For intListX = lstSelected.ListCount – 1 To 0 Step -1

If lstSelected.Selected(intListX) Then

lstAvail.AddItem lstSelected.List(intListX)

' If you are using the optional ItemData property array,

' add the following line to carry the "ItemData baggage" along ...

lstAvail.ItemData(lstAvail.NewIndex) = lstSelected.ItemData(intListX)

lstSelected.RemoveItem intListX

End If

Next

 

End Sub

 

The form then looks like this:

 

 

Note that the items that were selected in lstSelected were removed from lstSelected and added back to lstAvail.

 

Download the VB project code for this example here.

 

You'll notice that in the previous example, the code for cmdAdd_Click and cmdRemove_Click was identical, except for the names of the listboxes in question. This code could be consolidated into a single Sub that could be placed into a standard module and incorporated into any project where it is needed:

 

Public Sub MoveListBoxItems(lstListToAddTo As ListBox, _

lstListToRemoveFrom As ListBox)

Dim intListX As Integer

For intListX = lstListToRemoveFrom.ListCount – 1 To 0 Step -1

If lstListToRemoveFrom.Selected(intListX) Then

lstListToAddTo.AddItem lstListToRemoveFrom.List(intListX)

lstListToAddTo.ItemData(lstListToAddTo.NewIndex) _

= lstListToRemoveFrom.ItemData(intListX)

lstListToRemoveFrom.RemoveItem intListX

End If

Next

 

End Sub

 

With this Sub incorporated into your project, you could use the following code in the cmdAdd_Click and cmdRemove_Click events to call the MoveListBoxItems Sub:

 

Private Sub cmdAdd_Click()

MoveListBoxItems lstSelected, lstAvail

 

End Sub

 

 

Private Sub cmdRemove_Click()

MoveListBoxItems lstAvail, lstSelected

 

End Sub

 

Download the VB project code for this example here.

 

 

Checkbox-Style ListBoxes

 

VB5 introduced the Style property for ListBoxes, with the options 0 – Standard and 1 – Checkbox. The listbox examples we have been working with thus far all have had their Style property set to "0 – Standard" (which is the default style, and the only style of listbox available prior to VB5).

 

Checkbox-listboxes are seen in several Windows applications. In VB itself, if you go to the Project menu and select References, the following dialog box will be displayed (note that the "Available References" listbox is of the checkbox variety):

 

 

To incorporate a checkbox-listbox into your application, simply grab a listbox control from your toolbox and set its Style property to "1 – Checkbox". The combined checkbox-listbox functionality will be built-in. Be advised that when you use the checkbox style, the MultiSelect property must be set to "0 – None" (VB won't let you set it to "Simple" or "Extended"). This is because the checkboxes now implement the multiple-selection functionality – all the user has to do is click the checkboxes; they don't have to bother with holding down the Ctrl or Shift key while clicking.

 

As you do with the Standard style listbox, you determine which items the user selected by looping through the items in the listbox and testing the Selected Boolean property array. The only difference is in the visuals – with a standard listbox, all selected items appear highlighted; with a checkbox-listbox, the selected items have their checkboxes checked.

 

Following is a short demo of the checkbox-style listbox.

 

This is the form at design-time. It consists of a listbox named "lstTest", with the style set to "1 – Checkbox", and a few items added in the List property. It also contains a command button named "cmdTest".

 

 

The cmdTest_Click event procedure, which simply prints the selected items on the form, looks like this:

 

 

Private Sub cmdTest_Click()

 

Dim intX As Integer

 

Cls

Print "The selected items are:"

 

With lstTest

For intX = 0 To .ListCount - 1

If .Selected(intX) Then

Print .List(intX)

End If

Next

End With

 

End Sub

 

At run-time, after selecting a few items and clicking the Test button, the form looks like this:

 

 

Note that only the last item that the user checks will be highlighted; and this is true whether the user checked it to select the item OR to deselect it (clear the checkbox). Therefore, the fact that an item is highlighted does NOT mean that it is selected.

 

The item that is highlighted only affects the Text property of the listbox (looking at the form above, the value of lstTest.Text would be "item3", whether the user checked the box to select it OR to clear it). The Text property of the listbox is useful only when the user can make one selection from the listbox, NOT when they are doing multiple selections as is the case here. Therefore, you should always use the Selected property array to determine which items are selected in a checkbox-style listbox.

 

Download the VB project code for this example here.

 

 

*** BONUS MATERIAL ***

ListBox Procedures

Presented below are several examples of how to extend the functionality of the listbox. The remove duplicates, drag and drop, search, and tooltip examples are based on examples that have been posted on www.planet-source-code.com. The example showing how to add a horizontal scroll bar is based on information provided in the Microsoft article at this location: http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B192184. The example showing how to set the backcolor of individual items is based on an example by Aaron Young, a talented programmer who frequently contributes to programming forum sites.

 

Remove Duplicate Entries in a ListBox

 

This example incorporates a general Sub procedure that you can use to remove duplicate entries from a listbox. The code for the Sub is:

 

'-----------------------------------------------------------------------------

Public Sub RemoveListBoxDuplicates(pobjLB As ListBox)

'-----------------------------------------------------------------------------

 

'REMOVE DUPLICATES FROM LISTBOX

Dim intI As Integer

Dim intJ As Integer

With pobjLB

For intI = 0 To .ListCount - 1

For intJ = .ListCount To (intI + 1) Step -1

If .List(intJ) = .List(intI) Then

.RemoveItem intJ

End If

Next

Next

End With

 

End Sub

 

In the sample program, clicking the "Load ListBox" button loads the listbox with 100 entries, where an entry will be any one of 20 company names selected at random:

 

 

In the sample program, clicking the "Remove Duplicates" button implements the Sub procedure described above to remove all duplicate entries:

 

 

 

Download the sample program here.

 

Notes:

You can modify this procedure to work with a ComboBox by modifying the argument in the procedure header as follows:

 

Public Sub RemoveListBoxDuplicates(pobjLB As ComboBox)

 

You can modify this procedure to work with a ListBox OR a ComboBox by modifying the argument in the procedure header as follows:

 

Public Sub RemoveListBoxDuplicates(pobjLB As Control)

 

 

Drag and Drop within a ListBox

 

This example shows how you can rearrange the items in a listbox using drag and drop.

 

 

Download it here.

 

Variation: This example demonstrates how you can drag an item from one listbox to another; when the item is dropped into the target listbox, it replaces the highlighted item.

 

 

Search-as-you-type for an Item in a ListBox

 

This example shows how you can use a textbox in conjunction with a listbox to implement "search-as-you-type" functionality.

 

 

Download it here.

 

Show Tooltips for Individual Items in a ListBox

 

This example shows how you can show a tooltip for an individual item in a listbox when you move the mouse over the item. This can be especially useful for long items that do not fully display in the listbox. This technique can also be used for the FileListBox.

 

 

Download it here.

 

 

Add a Horizontal Scroll Bar to a ListBox

 

The normal VB ListBox that comes with does not have a horizontal scroll bar. This can be a problem when an item in a ListBox extends past the boundaries of the ListBox. We saw one way around this in the example above by using tooltips. This example shows how you can actually add a horizontal scroll bar to a listbox by calling the Windows API SendMessage function with the LB_SETHORIZONTALEXTENT constant.

 

 

Download it here.

 

 

Set the Back Color of Individual Items in a ListBox

 

This example uses subclassing to set the backcolor of individual items in a listbox.

 

 

Download it here.

What about the VBA Listbox control?

If you are not writing full blown VB6 applications but are instead working in Visual Basic for Applications, you will be pleased to know that most of what we have described above will apply for your VBA listbox as well. The properties and methods are in many cases identical and at the least very similar. Just new up or drag a vba listbox onto your access form for example and you will be off and running.

This article related to the VB6 and VBA Listbox was written By TheVBProgramer.

If you enjoyed this post, subscribe for updates (it's free)

listbox 1-checked

can i use listbox as checked from itemdata instead index.

how can i click a font on a

how can i click a font on a listbox example "Arial" then the label will change its font into an Arial??

Listbox Coloring

Hello,
Did you ever try to get different colors of listbox rows on MS Access 2003 form?
This does not seem to work.. It just hanges the application
Also, looks like NewIndex property is not supported in Access
Thank you

Need help with truncation of file names

Hello everyone,

Thank you for this lovely site and the amazingly simple tutorials.

My issue is that I am trying to make a form in VB6.0 which outputs the file names and just the filenames dragged and dropped into a listbox. I read through some books and surfed the internet to find a few codes, combined them and figured a way to finally let me drag and drop files and folders into a list box and returns their full names with path.

I do not want this code to return the full path on the list box. I also don't want it to list the folder names. The code is as follows:

Private Sub List1_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim ItemCount As Integer
Dim I As Integer
On Error Resume Next
ItemCount = Data.Files.Count
For I = 1 To ItemCount
List1.AddItem Data.Files(I)
Next
If Err Then Err.clear
End Sub

I have another code that displays filenames, and I was able to browse through the windows directory and the network to display just the filenames without the path and extensions. My issue is that it displays the hidden files too, which I don't want.
Can someone also help me with skipping hidden files so that my code just returns read-only or normal files? The code is as follows:

Private Sub ListFolder(sFolderPath As String)
Dim FS As New FileSystemObject
Dim FSfolder As Folder
Dim File As File
Dim I As Integer

Set FSfolder = FS.GetFolder(sFolderPath)
Text1.Text = ""
For Each File In FSfolder.Files
DoEvents
'truncation of drive path and extension
Dim posn As Integer, j As Integer
Dim fName As String
posn = 0
For j = 1 To Len(File)
If (Mid(File, j, 1) = "\") Then posn = j
Next j
fName = Right(File, Len(File) - posn)
posn = InStr(fName, ".")
If posn <> 0 Then
fName = Left(fName, posn - 1)
End If ' end of truncation code
GetFileName = fName
Text1.Text = Text1.Text & fName & vbCrLf
Next File
Set FSfolder = Nothing
End Sub

Looking forward for help.

tooltip and horizontal scroll

hey please help me out with the tooltip and also setting the horizontal scroll bar!! ...i cant understand the code :(. rest evrything in the tutorial is superb!!!!!!!!!!

Listbox end of file

I'm loading a file into a listbox and I want the listbox to show the last of the file not the beginning.
I have encluded the these statement at the end and it working fine, except the last line is a blank highlighted line. How do I get rid of this line or the highlight? Any help would be appricated.

List1.Refresh
List1.ListCount
List1.ListIndex = (J) - 1

Almost had it; Change last

Almost had it; Change last line from List1.listindex = (J) - 1 to list1.listindex = -1.
VB6 programmers 'YOU ROCK'.

computing 9691 vb6

hello!
i am trying to view the records of a particular table in my database(named db1.mdb) into a listbox in visual basic 6.0

can anyone help me with this?? your help will be highly appreciated! :D

ALSO REVERT ME

HI! THERE, THIS SIDE JOGINDER SINGH FROM MUKTSAR, I AM SEARCHING THE SAME PROJECT AS YOU ARE. ALSO SEND ME THE LINK OR SOURCE CODE FOR THE SAME PROJECT.

THANKS & REGARDS
JOGINDER SINGH
+91 99141 43808

Create a SQL select statement

Create a SQL select statement that defines what records you wish to view then set the .rowsource property of the list box to the SQL string then requery and presto you have your list.
I have included sample straight form a working project

Dim adF As Form_frmAdPeople
Dim sql As String

Set adF = Forms!frmAdPeople
sql = "SELECT tblRelationshipSubs.RelSubKey, tblRelationshipSubs.relSubName"
sql = sql & " FROM tblRelationshipSubs"
If adF.chkDeletedRelSub Then
sql = sql & " WHERE (((tblRelationshipSubs.fkRelationship) In (" & ReturnListSelections(adF.lstFilterRelationship, True, False) & ")) AND ((tblRelationshipSubs.recRelSubDeleted) Is Not Null))"
Else
sql = sql & " WHERE (((tblRelationshipSubs.fkRelationship) In (" & ReturnListSelections(adF.lstFilterRelationship, True, False) & "))AND ((tblRelationshipSubs.recRelSubDeleted) Is Null))"
End If
sql = sql & " ORDER BY tblRelationshipSubs.relSubName;"
adF.lstFilterReltionshipSub.RowSource = sql
adF.lstFilterReltionshipSub = Null
adF.lstFilterReltionshipSub.Requery

The resultant listing shown is set to depend on user interaction where the checkbox named chkDeletedRelSub is set to true or false and hence the select statement reflects the user choice then displays the results. The key to the results is in the last 3 lines of code. Everything preceeding is setting up the select statement.

Hope this helps

nice...but can you help me on

nice...but can you help me on my assignment..a program that using a listbox a two list box that you can put one item or one at time the value of the list box 1 to the listbox 2 and vice versa..listbox2 to listbox 1?will you help me?plllssss..=)

Tutorial

Excellent tutorial. It help me understand list boxes even more and more.
Thank you very much

Thanks For Ur Help I M

Thanks For Ur Help
I M Feeling Lucky
From Zoya

It's very cool. I like all of

It's very cool. I like all of these. Thank you.

Visual Basic storing multiple listbox items in 1 database field

I know its old but someone might find this helpful... To store multiple visual basic listbox selections in one db table field, concatenate or join the selected items with a text delimiter such as a pipe | or 2 colons :: OR most importantly, some unique text that will not be used in ANY of the available options...

AllSelected = item1Variable & "||" & item2Variable & "||" & item6Variable & "||" & item8Variable & "||" & item10Variable
INSERT/UPDATE DB with just the single variable AllSelected into your field

[were geeks so naked girls or tender moment with mom montage here...]

SELECT [AllSelected] FROM (where you put it) and get your multi items as a single variable from DB
Then Split the multi items in a single variable into an array of individual variables like this:

arrayAllSelected = Split(AllSelected, "||")
firstItem= arrayAllSelected (0)
second = arrayAllSelected (1)
third = arrayAllSelected (2)
fourth = arrayAllSelected (3)
fifth = arrayAllSelected (4)

This site saved me enough time that I had a moment to give back :) - thanks coder dude

How to come out from Multiple selection of items in listbox JAWS

In Listbox we select the multiple items using SHIFT+Down arrow. Pressing Enterkey will select and comeout from list box. JAWS(Screen reader) reads again same list box. tab key will move to next control and it will skip reading label text. so how to move to next field?

How to come out from Multiple selection of items in listbox JAWS

In Listbox we select the multiple items using SHIFT+Down arrow. Pressing Enterkey will select and comeout from list box. JAWS(Screen reader) reads again same list box. tab key will move to next control and it will skip reading label text. so how to move to next field?

I Love This

I Love This Tutorial.......
It Helped me a lot
Thanks!!!!!!!!!!!!!!!!!

plss help

Private Sub cmdAdd_Click()

Dim Num As Integer

Dim Arr(1 To 20) As String

Call addName(Arr())

End Sub

Private Sub addName(Arr() As String)

MsgBox "maximum of 20 Names only", vbInformation
a = InputBox("Enter student name:")
For Num = 1 To 20

Begin:
If a <> "" Then
Arr(Num) = a
lstArr.AddItem Arr(Num)
ElseIf IsNumeric(a) = True Then
MsgBox "Numbers are not allowed"
GoTo Begin
Else: MsgBox "Input Cant be null"
End If

Next Num

End Sub

guys why is it that this program doesnt follow the array size that i declare?plss help:(

add remove multiple items in listbox

For i As Integer = listbox1.Items.Count - 1 To 0 Step -1
If listbox1.Items(i).Selected = True Then
listbox2.Items.Add(listbox1.Items(i).Text)
listbox1.Items.Remove(listbox1.Items(i).Text)
End If
Next

Listbox Item background color

Your sample for changing the background color works great if all of the listboxes are on the main form....
What do I do to make it work when I place my listboxes on different frames to make a tabbed interface?
I modified the code for form load as follows:
lPrevWndProc = SetWindowLong(frame1.hwnd, GWL_WNDPROC, AddressOf SubClassedList)
and then only the listbox in that frame gets the change. Everything else shows the checkboxes.

I tried making lPrevWndProc an array and adding an index parameter to SubClassList,
but VB just blew up and closed on me.
Or is this a place where I might need to create a collection?

Any Help is appreciated.

snake ladder printing

is there a way of printing the contents of a list box with or without multiple columns to print the data on one page in columns?
m

Ayudame!

I am working on a project with my friend and we are having a problem with Active X control boxes. When the program we created starts the listbox runs automatically either once or two times when we open our program. My friend and I are trying to figure out how to either force the listbox to run twice (if it only runs once) or how to keep it from running at all (upon start up). We have a user interface where the user can select a choice and we display a message. (Just a note: The items in the listbox are referencing cells from another sheet and I am using Excel 2007 VBA.) Thank you (all) for any information you (all) can provide.

Find from listbox in VB.NET

PRITESH ( PINTOO )

========================================

Public Sub FindAllOfMyString(ByVal ListBox As ListBox, ByVal searchString As String)
' Set the SelectionMode property of the ListBox to select multiple items.
ListBox.SelectionMode = SelectionMode.MultiExtended
' Set our intial index variable to -1.
Dim x As Integer = -1
' If the search string is empty exit.
If searchString.Length <> 0 Then
' Loop through and find each item that matches the search string.
Do
' Retrieve the item based on the previous index found. Starts with -1 which searches start.
x = ListBox.FindString(searchString, x)
' If no item is found that matches exit.
If x <> -1 Then
' Since the FindString loops infinitely, determine if we found first item again and exit.
If ListBox.SelectedIndices.Count > 0 Then
If x = ListBox.SelectedIndices(0) Then
Return
End If
End If
' Select the item in the ListBox once it is found.
ListBox.SetSelected(x, True)
End If
Loop While x <> -1
End If
End Sub

Nice one: like it, like it.

Liking your work sir. Liking, your, work.

How to extract ID or name of

How to extract ID or name of the product from the selected record in the listbox.
please help in it.
thanks

How to scroll a sorted listbox

I have a listbox with sorted items.
Everey time I add an item, the list is sorted and reloaded into the list.
I want to scroll the listbox so the lastadded item is diaplayed at the bottom of the list, or if the last added item is not the last item in the sorted list, then I want it displayed as near to the center of the listbox as possible.

Example:
If the list shows 7 items and containd the entries
AAA
AAB
AAC
AAD
AAE
BAA
BAB
BAC
CAA
CAB
CAC
CBA
CBB
CBC
and I enter BBA, then the last entrered item BBA is not shown in the list after reload.
In thie case I want the listbox to display
BAA
BAB
BAC
BBA (my last entered item)
CAA
CAB
CAC

tia for assistance
Olav

If you are using:

If you are using: Listbox.AddItem "BBA"
to add your item to the list box,
You should be able to put: ListBox.ListIndex = ListBox.NewIndex
as the next line of code.

OMG!!!!!!!!!!!!!!

oh no!!! i need some codes on how to store the multiple value of listbox into the database instantly with just one click!!!!!

heyyy!!

the database is ms sql server 2005 so i will wait for your useful answers thanks!!!!!!

IT mode

What is the code for a list

What is the code for a list box where clicking item 1 will unload the form?????

Unload the form by clicking on a list item

the code for unloading a form is: Unload [Form Name]
If you want to unload the current form you can type: Unload Me
Me will returns the current form name...
The following code will unload the form when item #1 (Array Index = 0) on List1 is clicked:

Private Sub List1_Click()
If List1.ListIndex = 0 Then 'You can replace the 0 with any array index that you want
Unload Me
End If
End Sub

close by clicking

If your list box is named lst, try:

Private Sub lst_Click()
If lst.ListIndex = 0 Then Unload Me
End Sub

Note: The "first" item has index "0"

listindex

ive tried
listbox.listindex=0 then
it doesnt work,

>but the difference is that i try to retrieve and save fr0m ms access
example

adodc1.adoname=name of adodc
and the listbox datasource=adodc1, datafield=opt(table from ms access, which is also in listbox)

does this also work when the data is came from the ms acces?
thank you,

i have a project a Erollment System

Printing Selected ListView Items

I have a form with a ListView (checkboxes) and I want to know how to print to the local printer only the items that the user selects.

Printing

Try this (with lst being your ListBox):

Dim i As Long
For i = 0 To lst.ListCount - 1
    If lst.Selected(i) Then Printer.Print lst.List(i)
Next
Printer.EndDoc

Selecting All Fields with just one click

Hei,

I want to select all the fields in the listbox control in vb 6.0 with just one click.

Here is my code and I have written this code in the click event of listbox control.

Private Sub lst_Division_or_Team_Select_Click()

For i = 0 To lst_Division_or_Team_Select.ListCount - 1
lst_Division_or_Team_Select.Selected(i) = True
Next i

MsgBox "To Update You Need to Select All the Data Again Except Season Year", vbInformation

end sub

But my problem is that when I execute that code it will display message box on every time it select the line in the listbox.

can any one help me in this regards.

Thanks in advance.

Recursion

The problem is that setting Selected property raises the Click event again.
Try doing the following:

Private Sub lst_Division_or_Team_Select_Click()
Static SubRunning As Boolean
 
If SubRunning Then Exit Sub
SubRunning = True
 
For i = 0 To lst_Division_or_Team_Select.ListCount - 1
lst_Division_or_Team_Select.Selected(i) = True
Next i
 
MsgBox "To Update You Need to Select All the Data Again Except Season Year", vbInformation
SubRunning = False
end sub

Good luck!

Automate to click the listbox options

hi

i want to Automate to click the listbox options

Approved and Quoted

Cancelled

Expired

In progress

Not yet submitted

OPG

Lost

Won

Rejected

Re-submitted

please answer

i have table

table name (colddrink)

cdid, cdname, cdsize, cdprice
1 pepsi 250ml, 15
2 pepsi 1ltr 40
3 pepsi 1.5ltr 70
4 marinda 2.5ml 15
5 sprite 2.5ml 15
6 sprite 1ltr 40

now i want to display these values on webpage using datalist
like this format

pepsi
250ml, 15
1ltr 40
1.5ltr 70

marinda
250ml, 15

sprite
250ml, 15
1ltr 40

populate data from oracle in listbox

how to populate data from oracle to listbox .for this i'm doing as follows:

Dim oconn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strSQL As String
strSQL = "SELECT empno FROM emp1 "
Set oconn = New ADODB.Connection
oconn.Open "Provider=msdaora;Data Source=t212;User Id=treasury;Password=treasury;"
rs.CursorType = adOpenStatic
rs.CursorLocation = adUseClient
rs.LockType = adLockOptimistic
rs.Open strSQL, oconn, , , adCmdText
Dim i As Integer
For i = 0 To rs.RecordCount - 1
List1.AddItem rs 'showing error here
Next i

how to do this?and after populating data i want to
select i particular data from this list and
using this i want to populate a grid according to the no of employee obtained from listbox.for this i'm writting code as:

Dim a As Variant
'a = Val(List1.Text)

Dim oconn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strSQL As String
strSQL = "SELECT * FROM emp1 where empno=a " 'error is shown here
Set oconn = New ADODB.Connection
oconn.Open "Provider=msdaora;Data Source=t212;User Id=treasury;Password=treasury;"
rs.CursorType = adOpenStatic
rs.CursorLocation = adUseClient
rs.LockType = adLockOptimistic
rs.Open strSQL, oconn, , , adCmdText 'error is shown here

Set DataGrid1.DataSource = rs
End Sub

please advice some solution...

carriage returns in a list box...

Is there any way to force the listbox strings to allow carriage returns and other whitespace values? I would like to have a multicolumn listbox where the 2nd column data needs to be multiple lines, but all still part of the same value... for example:

Column 1 data | Column 2 data, 1st line
Column 2 data, 2nd line
Column 2 data, 3rd line

Where all 3 of the column 2 data lines associate to the column 1 data row.... I know... little confusing.

is it possible?

Only with OwnerDrawing

Yes, it is possible, but only with OwnerDrawing (much luck; that's very hard and dangerous);

There is no other solution (try to find some other control????)

Very good

Very good tutorial.............. Thanks a lot

Comment

Very concise & well written, if only all tutorials were this good. Saved me alot of time, thank you

Working with listboxes

This article reminded my of a lot of feature that i had forgotten about! Great Work! Thanks

Can I....?

I just want to display a very subtle horizontal line for each item in the list box to make it easier on the user's eye.. is this possible?

Can I Know....

can I know how to add valeus liisted in a listbox

buen tutorial

Thanks a lot......great place............great turorial..
Muchas gracias...magnifica pagina...magnifico tutorial

De-sellecting between two listboxes

Everything is great except... When you de-select from the right hand listbox and want the items to come back on the left hand listbox, they don't come back on the original place! The code shown above just adds them on the bottom of the left listbox!!

Informative, nice instructions, Great!

I have bookmarked your site.
thanks for your VB prowess and unselfishness to share your knowledge!

hey

I appreciate this fantastic site.... very good idea.... keep it Up.

Thanks

multi-column lists?

This is a fantastic round-up of all you can do with listboxes. I mostly use multi-column boxes and the sendmessage for example, I can't get the search as you type to work, I would really appreciate if you had some tips for it.
Thanks very much for everything.

Regards

John

can i ask for help

how to connect dblist in 6.0 to ms access,

write to .txt file from listbox

thnks for your help but there r still thing i cant do.

am doing a project where items are stored in a listbox (the items r stored from a text file (file2))
I need to update a file (file1) from all the items in the listbox.

any1 can help me

A very good Web page, where

A very good Web page, where we get a good/Details information.

Question

How to Assign Background color of Checkbox in a Listbox

Thank a lot

It's very fantastic. I don't know everything I need

Excellent article , Helped a

Excellent article , Helped a lot thanks again and again

addition in list box

how we can sum up the items in listbox or how we can perform addition in listbox

How To Add Icon Into ListBox?

Please Help How To Add Icon Into ListBox?

Google -> ListView

instead use ListView

Great Work

This page makes this website my hot favorite website

my Big Problem

iam Using Active Report to do reports and i want to select some feilds from Access data base by listBox
Set db = OpenDatabase(App.path & "\darf.mdb") ', False, False, ";pwd=" & "honda")
Set ss = db.OpenRecordset("edarat")
Dim i As Long
Dim tStr As String
Cls
With List1
For i = 0 To .ListCount - 1
If .Selected(i) Then
tStr = tStr & "," & .List(i)
End If
tStr = Mid(tStr, 2)
Next
Fifi = "Select * From edarat Where edara in('" & tStr & "') "
Set rr = db.OpenRecordset(Fifi)
Set ActiveReport2.DAODataControl.Recordset = rr
ActiveReport2.Show 1
End With

my problem is in this line
Fifi = "Select * From edarat Where edara in('" & tStr & "') "
it did not load that feild i selected

For i = 0 To .ListCount -

For i = 0 To .ListCount - 1
If .Selected(i) Then
tStr = tStr & "," & .List(i) ' ==== may be this is not right
End If
tStr = Mid(tStr, 2)
Next

For i = 0 To .ListCount - 1
If .Selected(i) Then
tStr = tStr & "' , '" & .List(i) ' === i think ..
End If
tStr = Mid(tStr, 2)
Next

Amazing

Excelent work :)

Question

Great tut, but how do you change the ForeColor of an item, instead of BackColor

Thanks

Oner Otomotiv

nice

tutorial

Excellent tutorial. It help me understand list boxes even more.
thank you

great work

yes.......realy..it is help ful me to gain knowledge ....

so i thanks you and i wish you to add more exampls to learn more.....

How to finds a string from the list

Article is great. Nobody can explain like this. Actually this is a light to the world of Visual Basic. I have one task related to this section. If possible please reply for the below mentioned tak.

Please also describe how to find a particular string from the list.

Suppose the entries are as follows:
Smith, John
Blow, Joe
Shoelaces, Tyrone
Nation, Bertha
Unger, Felix
Madison, Oscar
Joe Thomas

Now I want to know weather there is anybody with name containing "Joe". i.e., if I search the word "Joe", then two result should be returned. (1) Blow, Joe (2) Joe Thomas.

If there is any solution then please let me know.

Thanks

Jubin

Im not sure how to use your

Im not sure how to use your Drag to change List box order due to the fact that as soon as you click on the box it attemps to drap rather than when you actually drag...

listboxes for user output

that's an interesting topic, especially when you have two forms one for the input and another with a list box, for output

how can the list box be called from form1?

listboxes for user output

hey..

make your LISTBOX PRIVATE sub into PUBLIC sub...

..if your list box is in the form 2.. put this code in your form1.

Form2.NameofListinForm2.and so on...

Luar Biasa ok.............

Man Power Good......................................... TheVBProgramer

"www.vb6.us" is the best Bukan Basa Basi

Still a problem

I am still not able to combine check box and list of items in a Listbox. Its not well explained when i drag the check box into a Listbox and change property style to 1 it just brings a comand button.

Checkboxes

You do NOT have to insert a CheckBox, you simply set the Style property of the ListBox to 1, and every single item gets a checkbox.

Superb tutorial for beginners

I've been surfing the net for best tutorial but yours is superb.
thanks for sharing your time and knowledge. more power.
God Bless

Keep it up

Really have a great help for me

how to change or replace text of listbox at runtime ?

Very good link, but ....
how to change or replace text of listbox in vb.6 at runtime?

Tnx:

Lots of missing details...!

The author did not explain all aspect of ListBoxes and the 54 properties associated with it.

To cange the value ( text ) in tiy listbox use:

ListboxName.List(IndexValue) = string

Happy coding....

Great Job!!!!!!!!!!!

This is a knowledge sharing website....... You are done a very good job !!!!!!!!!

how do I make a listbox to view only, not allow selection

I need to list strings in a box and allow a scroll bar for client to scroll through but not allow the client to select an item
setting the enable control to false allows the data to scroll if I always set the ondex to (0) for each new item but it doesn't allow me to scroll when the box becomes full.

How to store multipel item in to database

Hi Friends
The given information was great!!!!

Friend's will you please tell me how can i store multipel selected list items into MS Access database within one field; and also tell how can i retriew it in different different field like different textboxes.

If possibel plese give basic coding for that.

Thank's to all helper...

helpful !!

helpful !!

Display columns of different fields in a ListBox

Didn't notice anything about formatting the listbox entries.
The following code provides 'columns' for different fields by using tabbing.
The columns property of the list box does not do this.

Public Const LB_SETTABSTOPS As Long = &H192
Public Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, lParam As Any) As Long

''''' THE FUNCTION ......
Public Sub SetTabs(lstListBox As ListBox, TabArray() As Long)
'clear any existing tabs
Call SendMessage(lstListBox.hWnd, LB_SETTABSTOPS, 0&, ByVal 0&)
'set list tabstops
Call SendMessage(lstListBox.hWnd, LB_SETTABSTOPS, _
CLng(UBound(TabArray)) + 1, TabArray(0))
End Sub

'''''' E.G OF HOW TO USE FOR 3 FIELDS ....
' FORM LOAD
Dim Tabs(2) As Long
Tabs(0) = 0
Tabs(1) = 100
Tabs(2) = 200
Call SetTabs (List1, Tabs)

List1.Additem "FIELD1" & vbtab & "ADDRESS" & vbtab & "ETC"

Display columns of different fileds in a Listview

Didn't notice anything about formatting the listbox entries.
The following code provides 'columns' for different fields by using tabbing.
The columns property of the list box does not do this.

Public Const LB_SETTABSTOPS As Long = &H192
Public Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, lParam As Any) As Long

''''' THE FUNCTION ......
Public Sub SetTabs(lstListBox As ListBox, TabArray() As Long)
'clear any existing tabs
Call SendMessage(lstListBox.hWnd, LB_SETTABSTOPS, 0&, ByVal 0&)
'set list tabstops
Call SendMessage(lstListBox.hWnd, LB_SETTABSTOPS, _
CLng(UBound(TabArray)) + 1, TabArray(0))
End Sub

'''''' E.G OF HOW TO USE FOR 3 FIELDS ....
' FORM LOAD
Dim Tabs(2) As Long
Tabs(0) = 0
Tabs(1) = 100
Tabs(2) = 200
Call SetTabs (List1, Tabs)

List1.Additem "FIELD1" & vbtab & "ADDRESS" & vbtab & "ETC"

Thanks for your help! It's

Thanks for your help! It's my lucky day!! :)

nice

that looks very nice, thx for sharing :)

SUPER !!!

SUPER !!!

tnx!!!!!

tnx 4 sample visual basic programs!!!!

List Boxes

Man...!!! I'm glad I found your site...

I dont get how to add

I dont get how to add horizontal scroll bars still

Fantastic

That was a really amazing article - the tooltips section was awesome - a lot simpler than the previous method I'd been using and considerably more stable. There's some other things I didn't know about either... coloured back sections - woo. :)

Thanks very much to the author!

A great tutorial

Can't say excep FANTAAAAAAAAAAAAAAASTIC....

Nice

That was Hella nice