Keep the ListView item higlighted

  • Thread starter Thread starter Asheesh
  • Start date Start date
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
 
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;
 
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.
 
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.
 
Back
Top