Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete an item from a list box - how to? 1

Status
Not open for further replies.

IlyaRabyy

Programmer
Nov 9, 2010
566
0
16
US
Colleagues,
I have a ListBox with the number of items in it, and USer needs need to remove one or two of these items, which he added erroneously. So, (s)he highlights them and clicks "Delete" button.
In the past (and another programming language) it was simple, something like this:

Code:
For I =  lstFiles.Items.Count -1 To 0 Step -1
	If lstFiles.Items(I).Selected() Then
		lstFiles.Items(I).Delete()
	End If
'Next

Ain't working in VS 2019 VB .NET, it throws exception:

2023_02_20_14_30_ListBoxItemDeleteErrs_sg4xbs.jpg


Neither works the following:

Code:
lstFiles.ClearSelected()
lstFiles.Refresh()

It just don't do anything (albeit neither throws exception).

Please enlighten this "dinosaur" on how nowadays one does deletion of the selected items from a ListBox?

TIA!


Regards,

Ilya
 
Colleagues,
The solution was found, and ridiculously simple one:

Code:
For I As Int32 = lstFiles.Items.Count - 1 To 0 Step -1
	
	If lstFiles.SelectedIndex() = I Then
		lstFiles.Items.RemoveAt(I)
	End If
	
Next I

Does anyone have a more simple solution?

Regards,

Ilya
 
Er ... that doesn't do quite what you think it does, I'm afraid.

It only removes the first selected item. If you have selected more than one item the remainder will not be removed.

Try the following:

Code:
[COLOR=blue]For i As Int32 = lstFiles.SelectedItems.Count - 1 To 0 Step -1
    lstFiles.Items.Remove(lstFiles.SelectedItems(i))
Next
lstFiles.ClearSelected()[/color]

 
Tried your suggestion, StrongM, thank you!
Alas, it erred:

2023_02_22_09_34_OD_Tools_2022_Debugging_MultiForm_cmdDel_From_ListBox_nsn3dt.jpg


Something I'm missing, but - what?

Regards,

Ilya
 
Because you have are not using my code. You are incorrectly using a mix of your code and my code.
 
That worked.
Thank you!
Problem solved.

Regards,

Ilya
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top