Selecting a ListView Item





1.00/5 (1 vote)
Code to add an item to a ListView control and fully select that item.
Recently, I was writing a C# desktop application that processed records from a database. I wanted to provide visual feedback as to what was going on so I decided to add each record to a ListView
control as the record was processed.
In order to highlight the current item, and also to scroll the ListView
control as needed in order to keep the current item visible, I decided to select each item after I added it to the list.
I was surprised to find that there is no single method that will select an item as though it was clicked with the mouse. You can select an item by setting its Selected
property to true
. But the ListView
control allows multiple items to be selected, and so selecting an item does not unselect any already selected items.
Also, when you click on a ListView
item, it also gets a focus rectangle drawn around it. This is a type of dotted line that shows which item is the current item. (Note that the focus rectangle is only drawn when the control itself has the focus.)
And finally, when you click on a ListView
item with the mouse, the ListView
will scroll, if needed, so that the newly selected item is fully visible within the ListView
’s client window area.
As I mentioned, there is no single method to duplicate all the actions that occur when you click on a ListView
item with the mouse. The code I ended up with to add an item to a ListView
control and fully select that item is shown in Listing 1.
ListViewItem item = new ListViewItem();
lvwInfo.SelectedItems.Clear();
lvwInfo.Items.Add(item);
lvwInfo.EnsureVisible(item.Index);
item.Selected = true;
item.Focused = true;
I don’t understand why a higher level method is not provided to accomplish this same task. Not only would that save the time required to find all the individual methods required to accomplish this, but it’s possible that the control could change in the future to require an additional or different step. Having this logic as part of a single method in the control allows the control developers to make changes as needed, and all code that uses that control would then work correctly.