ListView.SelectedItems is always empty

M0ment 41 Reputation points
2022-01-01T18:55:57.277+00:00

Hello there. I have the following code:

private void folderView_SelectedIndexChanged(object sender, EventArgs e) {
            libraryExplorer.selectedItems.Clear();
            libraryExplorer.selectedItems = folderView.SelectedItems;
            if (folderView.SelectedItems.Count == 1)
                toolStrip.Items[1].Enabled = true;
            else
                toolStrip.Items[1].Enabled = false;
        }

What it does, is it enables the "Rename folder" button in a toolStrip if only one item is selected, if not, it disables it. The libraryExplorer is a class I created with functions that helps with other stuff, so that doesn't matter.
My problem is, that folderView.SelectedItems.Count always returns 0.
I am not programmatically setting any selected items. You can only select stuff by clicking and the ListView has multiSelect set to true. (Although that's another problem I have to tackle, multiSelect doesn't work even if it is true, holding control doesn't do anything)

It could be that I am misunderstanding how a ListView works, and I would be extremely happy if someone enlightened me. :)
With regards,
Alvin.

Developer technologies Windows Forms
Developer technologies C#
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2022-01-02T18:11:15.847+00:00

    Try removing the libraryExplorer.selectedItems.Clear( ) line.

    This should also solve the problem of MultiSelect, which apparently does not have effect.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2022-01-01T19:55:28.997+00:00

    Make sure MultiSelect is enabled for folderView

     .folderView.MultiSelect = true;
    

  2. Tony Hill 1 Reputation point
    2022-01-02T15:35:16.98+00:00

    I have come across this before, don't try and test for the number of selected items in the SelectedIndexChanged event use the ItemSelectionChanged event.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.