Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an item in a ListView programmatically?

I'm trying to select the first item in a ListView programmatically, but it doesn't appear to have been selected. I am using the following code:

if (listView1.Items.Count > 0)     listView1.Items[0].Selected = true; 

Actually I've had this problem before but I can't remember how I managed to solve it!

like image 644
Homam Avatar asked Apr 26 '11 13:04

Homam


People also ask

How to select item from list View in c#?

To select an item in a ListView, we can use the SetSelect method that takes an item index and a true or false value where the true value represents the item to be selected. The following code snippet sets a ListView to allow multiple selections and selects the second and third items in the list: ListView1.

Which method is used to obtain the selected option from a ListView?

To get which item was selected, there is a method of the ListView called getItemAtPosition.


2 Answers

Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.

  1. The simple solution is to set the focus to the ListView first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load event, or immediately after you set the Selected property:

    myListView.Select(); 

    The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).

  2. To fix that, you will need to set the HideSelection property of the ListView control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.

    When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.

    You can set this property either at design time, or through code:

    myListView.HideSelection = false; 
like image 192
Cody Gray Avatar answered Nov 09 '22 05:11

Cody Gray


if (listView1.Items.Count > 0) {     listView1.Items[0].Selected = true;     listView1.Select(); } 

list items do not appear selected unless the control has the focus (or you set the HideSelection property to false)

like image 20
VikciaR Avatar answered Nov 09 '22 03:11

VikciaR