Joey Joey - 7 days ago 6
Vb.net Question

How do I rename/replace text in a ListBox?

I have a

ListBox
filled with directories of files, e.g
C:\Logs\2016-09-28-2.log
, I need to rename all of the
.log
's to
.log.gz
(only in the ListBox, not the actual file)

There are multiple
.log
files within this
ListBox
, so I will need it to go through the whole list renaming all of the
.log
's to
.log.gz
.

I have researched but the only solutions I found were for
TextBoxes
, which then didn't work for the
ListBox
.

Answer

Assuming that you are using WinForms, you can modify the properties of items in a ListBox via the Items property. This returns a ListBox.ObjectCollection. You can index into this collection and modify the individual items.

Generally, items in a ListBox are just strings, so assigning a new string to the appropriate index in the Items collection will change the text in the ListBox. However, they can actually be any type of object. Check the code that adds the items to the ListBox in the first place to make sure that they are strings. If they are something else, you'll need to modify that data structure accordingly.

To do this for all of the items in the list, you will need to use a loop that loops through the entire Items collection.

For example:

For i As Integer = 0 to myListBox.Items().Count
    myListBoxItems.Items(i) = myListBox.Items(i) + ".gz"
Next

If it is not guaranteed that all items in the ListBox should have the .gz extension added to them, you will need to use a conditional statement inside of the body of the loop that first tests the current value of the string to decide whether to append the extension.

Comments