Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Force selection of a an item in a ListView

Status
Not open for further replies.

Narzul

Programmer
Jun 28, 2005
3
CA
Hi folks,

How can I force the selection of a item (by code) in a list view ? (In details view of course).

Thanks a lot.
 
Hmm the selected property is there, but even if I do this, the listview UI don't hightlight the selected item..
 
ListViewItem item = this.lstResults.Items[0];
item.BackColor = Color.Blue;

You can manually set the background and clear it each time. I remember listviews being a bit of a pain for this.
 
Thanks, if you want the best effect :

listView1.Items[0].Selected = true;
listView1.Items[0].BackColor = SystemColors.Highlight;
listView1.Items[0].ForeColor = Color.White;

 
My Final Suggestion: Create your own usercontrol extending the ListViewItem. Add a property called IAMSELECTED and when set to true, you apply those settings. When false, set back to default.
 
The right way to do it is to set your Item[x].Selected properties like you are and then do listView1.Select();
 
Thanks for coming out rdgerken,

But what happens when you lose focus of the control or the form?
 
JurkMonkey,

Narzul simply asked how to select an item programmatically in a listview, how do you know he wants to do this from another form? He never mentions that anywhere in his post, and also, I don't believe there is an issue with losing focus on the control... the form maybe. I think your method would be needed if you wanted to do this without having focus on the form, I'm not sure. I suppose if you had a reference to that control, the Select() would still work, I have not tried that myself. Anyways, I thought that I'd throw that out there in case he hadn't thought of that. It's a much easier way to select an item in a listview if you are on the same form. Perhaps I could refrain from using "the right way" in future posts, as we all know there are many many ways to do the same thing.

I see you on here a lot, and you are one the better programmers, and your help is always most appreciated.
 
rdgerken,

After playing with the approach you suggested I have to say: it works quite well.

Good suggestion.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top