Adding Items to the other listbox from the first listbox RRS feed

  • Question

  • Suppose I have two listboxes Listbox1 and Listbox2

    Now I have some filename string as items in Listbox1, Now I have the procedure to delete the selected item from the listbox1, I am using a try/catch so that if some file does not delete due to permissions so my program should handle the exception, I want that when this comdition happens if some file is not able to delete, that particuular filename should be added to the listbox. Can someone help me out, I am attaching my code below in which i need some help and corrections so my requirements meets.

    For i = listbox1.Items.Count - 1 To 0 Step -1
                    If listbox1.CheckedIndices.Contains(i) Then
                        Catch ex As Exception
                        End Try

    Thanks in advance.

    Monday, August 12, 2013 8:40 PM


  • Hello,

    Looks like you are using a CheckedListBox not a ListBox. You can process items via LINQ, get only checked items text and do what you want. We can get the text and ordinal position too.

    The code below will get only checked items then add them to normal ListBox. In the for/next you would do your delete and on failure do the Add to the ListBox. Please excuse the names I used for the procedure and second parameter my brain is out there right now.

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub WhatEver(ByVal sender As CheckedListBox, ByVal Other As ListBox)
        Dim Items =
                From Item In sender.Items.Cast(Of String)() _
                .Where(Function(xItem, Index) sender.GetItemChecked(Index)) _
                .Select(Function(a, b) New With {.Index = b, .Text = a})
        For Each item In Items
    End Sub

    To try this out, download this project and add a ListBox and button. Add this code to the button

    Place the first code block in the module ExtensionMethods.vb and this works for you add the code to your project.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Monday, August 12, 2013 10:00 PM