Home > Enterprise >  Unselect a listbox item if it contains a specific character (don't allow its selection)
Unselect a listbox item if it contains a specific character (don't allow its selection)

Time:06-17

I have a listbox1 with a list of items. If a user has to select an item with a single mouse click and if that selected list item has an equal sign in it, it must immediately display a message stating this and deselect the item.

I have looked at various solutions all of which does not work as I want it to:-

Below is my code which works ummmm most of the time but not when two or more items have already been previously selected. I need a always will work solution.

    Private Sub ListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseClick

    For I = 0 To ListBox1.SelectedItems.Count - 1
        If Not ListBox1.Items(I).ToString.Contains("=") Then
            ListBox1.SetSelected(I, False)
            '  MsgBox("Please only select items that have = in description ! ! ! Edit item if you want to include . . .", MsgBoxStyle.Critical)
        End If
    Next
    ListBox1.Refresh()

End Sub

CodePudding user response:

I think it's better using SelectedIndexChangedEvent:

Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

    With CType(sender, ListBox)
        If Not IsNothing(.SelectedItem) AndAlso .SelectedItem.ToString.Contains("=") Then
            MsgBox("Invalid selection.")
           .SelectedItem = Nothing
        End If
    End With

End Sub

CodePudding user response:

One solution for this problem is to get - in the SelectedIndexChanged event - the indices of the invalid selections if any to deselect them and show the message. Handling the SelectedIndexChanged event in particular is to make it work with the mouse and keyboard inputs.

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
    Handles ListBox1.SelectedIndexChanged

    With ListBox1
        Dim invalidSel = .SelectedIndices.Cast(Of Integer).
            Where(Function(i) Not .GetItemText(.Items(i)).Contains("="))

        If invalidSel.Any() Then
            RemoveHandler ListBox1.SelectedIndexChanged,
                AddressOf ListBox1_SelectedIndexChanged

            For Each i In invalidSel
                .SetSelected(i, False)
            Next
            MessageBox.Show("Please....")

            AddHandler ListBox1.SelectedIndexChanged,
                AddressOf ListBox1_SelectedIndexChanged
        End If
    End With

End Sub

Note, removing then adding the handler again is to avoid showing the message box repeatedly in the multi-selection modes. Without it, the event fires for each .SetSelected(i, False) call.

  • Related