Getting a specific ListBox Index


Could someone please help me out.

So I have this issue where I want to automatically edit a certain cell using a name i have stored in a variable.

This is what i have to edit contents of a certain row and column in a static way by specifying the row, which in this case is “0”, i need to dynamically find the row index using the name i have stored in a variable, which in this case is exactly the same as the name in the row i want to edit.

Dim Hostname As String = "SomeValueJustForExampleWhichIsDefinedEarlierInMyCode"

ListBox1.Cell(0, 1) = Hostname
ListBox1.Cell(0, 3) = "Online"

This is basically what i need if it was possible, getting the row index by looking for it with the name(The name in the variable and the name in the listbox row column 1 is exactly the same)

ListBox1.Cell(Hostname, 1) = Hostname
ListBox1.Cell(Hostname, 3) = "Online"

How the whole thing works is I have a listbox that populates with a range of virtual servers from a database, statically. Then I get dynamic data every second to update each specific row and column accordingly, so I need a way to tell the dynamic data which row is the correct row to update. The “Hostname” and “Online” columns is just an example, there are a few more columns which needs to be updated dynamically.

If anyone would kindly assist me, I got stuck at this ridiculously simple part.

Thanks in advance,

  • Dian

You need to loop through the listbox from row index 0 to listcount - 1 in order to find the row that you are trying to edit.

Something like this:

for i as integer = 0 to ListBox1.ListCount - 1 if ListBox1.Cell(i,1) = hostname then // Do whatever editing you need here using the index i end next

You can also use Exit For to exit the loop once you’ve updated the row.

Also, just as an additional note, if you want to use this method to remove a row (assuming that you aren’t exiting the for loop early as @Wayne Golding suggested) then you will need to loop through from the end of the list to the beginning, otherwise you will run into an index that doesn’t exist.

for i as integer = ListBox1.ListCount - 1 downto 0 if ListBox1.Cell(i,1) = hostname then ListBox1.Remove(i) end next

Thanks Jared and Wayne, Let me quickly attempt to put your advice into action. It seems like it would work perfectly!

Woah guys this was my perfect solution, It is working better than I ever imagined.

Thank you so much!