Keep the ListView item higlighted

A

Asheesh

Hi All,

I'm using a listview control in which I highlight the first item in the
listview control using lv.Item[0].Selected=true.
This works fine, but if there are only 2 items in the listview control, and
I press on any other area within the listview control, the highlighted
becomes unhighlighted.

Upon this when I try to access the property
lvTranslations.Items[lvTranslations.SelectedIndices[0]].SubItems[1].Text, I
receive an ArgumentOutofRangeException, which is correct since there isn't
any item highlighted currently.

Is there a way whereby I can prevent the user from unhighlighting the
highlighted item, or is there any other way to access the selected item?

Please help!

Regards,
Asheesh
 
G

Ginny Caughey [MVP]

Asheesh,

You can use an event handler for SelectedIndexChanged that looks something
like this:

if(myListBox.SelectedIndex == -1 || myListBox.SelectedIndex >
myListBox.Items.Count -1)
myListBox.SelectedIndex = 0;
 
G

Ginny Caughey [MVP]

Asheesh,

Before retrieving the Text property, check that the listview's
SelectedIndices.Count > -1 and FocusedItem != null. You can do this is your
SelectedIndexChanged event handler to know when to reset the selected index
to the first one again if that is what you want to do.
 
G

Ginny Caughey [MVP]

Asheesh,

You can use the SelectedIndexChanged event handler to check that both the
SelectedIndices.Count > -1 and that FocusedItem != null. You can then reset
the focus to the first item if you choose.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top