Circular listview

  • Thread starter Thread starter Alberto
  • Start date Start date
A

Alberto

I need a listview where the user can select the items with the arrow keys
but I also want that it works in a circular way: if you are in the first
item and press key up, the last item is selected (the same with the last
one).

I wrote this code for the keyDown event of the listView:

if (lst.SelectedIndices.Count > 0)
{
if (lst.SelectedIndices[0] == 0 && e.KeyCode == Keys.Up)
{
lst.Items[lst.Items.Count-1].Selected = true;
}
else
{
if (lst.SelectedIndices[0] == lst.Items.Count-1 &&
e.KeyCode == Keys.Down)
{
lst.Items[0].Selected = true
}
else
{
if (e.KeyCode == Keys.Down)
lst.Items[lst.SelectedIndices[0]
+ 1].Selected = true;
else
if (e.KeyCode == Keys.Up)
lst.Items[lst.SelectedIndices[0]
-1].Selected = true;
}
}
}

But there are two problems:

1) when the first item is selected and press key up two times and then press
key down.
2) when the last item is selected and press key down two times and then
press key up.

Can anybody tell me whats wrong?
Thank you very much.
 
Hi Alberto,

I modified your code a bit, using a switch and writing the code based on
which key is pressed.
You need to set both selected status and which item has focus. You also
need to test for the Shift key.

Since holding shift means multiselect and releasing shift means clear the
selection you need to handle all up and down events as well as mark the
event as handled or the default behaviour will mess things up.

Put this code in your keydown event:

switch(e.KeyCode)
{
case Keys.Up:
if(Control.ModifierKeys != Keys.Shift)
foreach(ListViewItem l in lst.SelectedItems)
l.Selected = false;

if(lst.FocusedItem.Index == 0)
{
lst.Items[lst.Items.Count - 1].Selected = true;
lst.Items[lst.Items.Count - 1].Focused = true;
}
else
{
lst.Items[lst.FocusedItem.Index-1].Selected = true;
lst.Items[lst.FocusedItem.Index-1].Focused = true;
}
e.Handled = true;
break;
case Keys.Down:
if(Control.ModifierKeys != Keys.Shift)
foreach(ListViewItem l in lst.SelectedItems)
l.Selected = false;

if(lst.FocusedItem.Index == lst.Items.Count - 1)
{
lst.Items[0].Selected = true;
lst.Items[0].Focused = true;
}
else
{
lst.Items[lst.FocusedItem.Index+1].Selected = true;
lst.Items[lst.FocusedItem.Index+1].Focused = true;
}
e.Handled = true;
break;
}
 
Back
Top