I have a listview on a Win Forms where I need to programmatically set the selected index. Apparently, ListView does not have a SelectedIndex property that can be set. Is there another way to do this?
-
There is an event - SelectedIndexChanged that you can configure to do what you need. – RizJa Dec 11 '15 at 17:10
-
4`listView1.Items[0].Selected = true;` – TaW Dec 11 '15 at 17:13
-
@TaW you should post that as the answer with a little explanation. – The Sharp Ninja Dec 11 '15 at 17:19
2 Answers
Apparently, ListView does not have a SelectedIndex property that can be set.
Indeed and it is logical as you can have multiple Items selected.
Hence it does have the SelectedItems and also the SelectedIndices property; both are read-only.
To select an Item simply set its Selected property to true:
listView1.Items[someItemIndex].Selected = true;
If the ListView' s MultiSelect property is false, this will deselect all other Items. If it is true the Item is added to the set of selected Items..
To de-select all Items in one go, use listView1.SelectedIndices.Clear(); or listView1.SelectedItems.Clear();..
- 53,122
- 8
- 69
- 111
-
It seems you post the comment and me the answer concurrently. +1 to your answer :) – Reza Aghaei Dec 11 '15 at 17:31
-
To select only one item, it seems it's enough to set `MultiSelect` property of the `ListView` to false and just select the new item. – Reza Aghaei Dec 11 '15 at 17:36
-
Yes. But maybe multiselect is still required and only the selection shall be reset. I tried to cover all aspects.. Calling `Clear` once is clearer than clearing and re-setting MulitSelect, imo. – TaW Dec 11 '15 at 17:38
-
I didn't thought of testing the `MultiSelect` property to `false` when I wrote the code, and the code seems useless now. – Reza Aghaei Dec 11 '15 at 17:39
You can select or deselect an item by setting the Selected property, for example: this.listView1.Items[2].Selected = true;
Edit
To select only one item, it's enough to set MultiSelect property of the ListView to false and just select the new item.
- 120,393
- 18
- 203
- 398