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!
I think that the problem and the solution was descripted by cody gray! I've an additional note.
Please check the focus of the specified listview item (and the control!). I could set the focus and the selection with the following lines of code :
this.listView1.Items[1].Selected = true;
this.listView1.Items[1].Focused = true;
But the focused control was a condition!
I know this is an old question, but I think this is the definitive answer.
listViewRamos.Items[i].Focused = true;
listViewRamos.Items[i].Selected = true;
listViewRemos.Items[i].EnsureVisible();
If there is a chance the control does not have the focus but you want to force the focus to the control, then you can add the following line.
listViewRamos.Select();
Why Microsoft didn't just add a SelectItem()
method that does all this for you is beyond me.
int i=99;//is what row you want to select and focus
listViewRamos.FocusedItem = listViewRamos.Items[0];
listViewRamos.Items[i].Selected = true;
listViewRamos.Select();
listViewRamos.EnsureVisible(i);//This is the trick
if (listView1.Items.Count > 0)
{
listView1.FocusedItem = listView1.Items[0];
listView1.Items[0].Selected = true;
listView1.Select();
}
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)
ListViewItem.IsSelected = true;
ListViewItem.Focus();
Source: Stackoverflow.com