Listbox Add/Remove Item AC2000
How to Add and Remove an Item from a Listbox in Access 97 or 2000
Q: How can I add and remove items from a Listbox in Access
A: In my
Access 321 class, I spend a great deal of time teaching you how to
work with unbound Listboxes to store temporary lists of information. I
show you the AddItem and RemoveItem methods of the Listbox object. The
problem is that these methods weren't added until Access XP (2002). So
if you have Access 97 or 2000, you can't use them. Listbox controls
existed back then, but you had to directly access the RowSource property
in order to do anything.
The RowSource property is essentially a list of the items in the box
separated by semicolons. It's not hard to work with, but you just have
to understand how to deal with text strings.
So, in this lesson, I'll show you how to essentially create your own
AddItem and RemoveItem code. First, we'll start out creating a simple
unbound form with an unbound Listbox (MyList), an unbound text box (MyText)
and two buttons (AddButton, RemoveButton). Make sure the Row Source Type
property of the listbox is set to Value List.
We want to type some data into MyText and then click on the Add button
to add that information to our list box. So here's the code we need to
put in the AddButton build event:
MyList.RowSource = MyList.RowSource & MyText & ";"
Now go ahead and save it. Type a name into the text box, and then click
Add. It should be added to the listbox.
That was the easy part. Basically we're just adding text string values
on to the end of the RowSource of the listbox. Now to remove items, it's
a little tougher. Essentially if the word "Joe" is typed in to the box
and someone clicks Remove, we need to find "Joe;" in the RowSource and
remove it. Here's the code I used:
Dim S As String
S = MyText & ";"
MyList.RowSource = Replace(MyList.RowSource, S, "")
I basically create my own string equal to whatever was typed into the
MyText textbox plus a semicolon. Then, I'll use the Replace function to
change that string into an empty string, effectively removing it from
If you want to remove the item from the box that the user clicks on
instead of having to make them type it in the text box, then you just
need to know how to set the text box equal to whatever the user clicks
on. You can do that with an OnClick event for the Listbox:
MyText = MyList.ItemData(MyList.ListIndex)
This will now set MyText equal to whatever value is currently clicked on
in the list box. Then if the user clicks on Remove, the value is set for
the remove operation.
So there you have it. That's how you would add and remove items from a
listbox in Access 97 or 2000 without the AddItem and RemoveItem methods.
This will allow you to now follow all of the examples in