Click here to Skip to main content
15,798,200 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all

I have a ListView populated with several items (ListViewItem) items.
I want to do 2 things with these items.   

1) I want to prevent some items from being selected (based on some critera that I define). 

What I have tried:

Updated 12-Jul-23 4:44am

From what I can see, you cannot set a List View Item to be not selectable.

Other things you can do;

a) Add an event handler for the ItemSelectionChanged and handle it there
b) Use checkboxes and add an event handler for the ItemCheck/ItemChecked event

Kind Regards
Share this answer
Here is a very simple solution using the SelectedIndexChanged event handler for the ListBox control.

I'm checking to make sure the index is greater than -1 as that is an invalid index (-1 means nothing is selected). You can modify this as needed but as it stands the snippet makes it so any listbox item clicked on with the value "I can't be selected" will then clear all items selected. Use this event handler as you wish.
Hint: Change the backcolor of items :p

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    If ListBox1.SelectedIndex > -1 And
        ListBox1.Items(ListBox1.SelectedIndex) = "I can't be selected" Then
    End If
End Sub
Share this answer
Here is another example to disable a listview item using combination of checkbox and ItemCheck Event. There also explanation on how to grey out the item.

c# - How do you disable an item in listview control in .net 3.5 - Stack Overflow[^]
Share this answer
Very late, but it could be usefull for others :)

Using MVVM, you should bind the IsHitTestVisible property of the ListViewItem to a property of your business object.

An example:
We have a list of clsMyClass object, used as ItemsSource for our list.
The class clsMyClass has a boolean property IsSelectable
Our XAML shoul be like this:

<listview itemssource="{Binding MyList}" selectionmode="Single"> <listview.itemcontainerstyle>
<Setter Property="IsHitTestVisible" Value="{Binding IsSelectable}"></setter>

In this way the items with IsSelectable=False will be not visible to the hit test, which means that the ListView will not intercept the mouse events and will not select it once clicked.

Note: this solution is not perfect in a multi-selection environment, because all items can be selected anyway using keybord shortcuts like Ctrl+A or Shift during selection.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900