Help deleting some listbox items

ALIG

New member
Joined
Jan 31, 2006
Messages
2
Programming Experience
Beginner
hello!

i'm a new member at the forum and i'm starting to work with
Visual basic.
I'm having some problems and need help deleting some listbox items.

Example:
Private Sub cmdapg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdapg.Click
If MsgBox("Are you sure you want to delete?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
For n As Integer = 0 To Me.lstfiles.Items.Count - 1
Me.lstfiles.SetSelected(n, True)
?????

Tanks
 
VB.NET:
Expand Collapse Copy
Me.LstFiles.RemoveAt(n)

The above code wil remove at the specified index. There is also a Remove method that will remove a specific
item.

Just one more little point.. MsgBox part of 'Old' VB the .NET way to do it is...

VB.NET:
Expand Collapse Copy
MessageBox.Show
 
I'm guessing that you are trying to delete all the selected items. Note that removing items from a collection in a loop is an error-prone operation. Lets say that you have three items in a collection and you want to remove the second and the third. If you remove the second item then you collection only has two items left, so you now have no third item to delete. It's this type of thing that causes unexpected behaviour and unhandled exceptions. There are two simple and safe ways to remove all selected items from a ListBox in a loop:
VB.NET:
Expand Collapse Copy
        'Work backwards.
        For i As Integer = Me.ListBox1.Items.Count - 1 To 0 Step -1
            If Me.ListBox1.GetSelected(i) Then
                'Remove the last selected item.
                Me.ListBox1.Items.RemoveAt(i)
            End If
        Next i

        'Use a While loop and two different collections.
        While Me.ListBox1.SelectedItems.Count > 0
            'Remove the first selected item.
            Me.ListBox1.Items.Remove(Me.ListBox1.SelectedItems(0))
        End While
Do not use a For loop and step forwards and do not use a For Each loop.
 
Can you help me..

Hi,
I am facing a problem, and searching a sollution for that and i found this mail, here you have provided the code to remove selected items from a list box, but my problem i have two list box and i want to add selected item listbox1 to listbox2 and same time i want to remove that item from listbox1, adding part is happens without any problems but real challenge is to remove that item from listboxa1 which is databound (Datasource is dataset) if i try and remove that selected item it pops up error message saying Items collection cannot be modified when the DataSource property is set
can anybody guide me how to remove item from a listbox which is databound

Thanks & Regards
Praveen
 
Back
Top