0
votes

Update!

To clarify the question. I would like to change the selected item in my listview by using the up and down arrow. I have tied keydown to a textbox. If a user presses the period key i make my listview visible. But it's not focused, that is why I have tied the keydown events to the textbox to be able to change the selecteditem in the listview.

the code that visuaƶ studio is complaining about is this

index = listView1.SelectedIndices[0];

the zero is somehow wrong?

I'm using a listview!

How do I change the listview selecteditem programatically? I'm currently listening to to the keypress events of up arrow and down arrow.

As they are pressed I would like to change the selected items index. So that it would behave equally as when pressing up or down arrow having it focused!

I have been trying, but it gives me an ugly error message.

Argument out of range exception with the additional information that goes like this:

Value of 0 is not valid for index. Here's my code for down arrow.

IT really should work I'm totally clueless about this!

if (e.KeyCode == Keys.Down)
{
    if (listView1.Visible)
    {
        index = listView1.SelectedIndices[0];  
        index = index - 1;
        this.listView1.Items[index].Selected = true;
    }
}

and for up arrow

if (e.KeyCode == Keys.Up)
{
    if (this.listView1.Visible)
    {
        index = listView1.SelectedIndices[0];
        index++;
        this.listView1.Items[index].Selected = true;
    }
}
1
Welcome to Stack Overflow. In the future, please provide the exact error or exception you're receiving, including as much detail as possible. Paraphrasing the error message does none of us any good. - Jesse Hallam
Where are you getting the exception? For the key up or for the key down? For me it looks like you don't have any items in the list and therefor get an index out of bound when you accessing item 0. - Tomas Jansson
I don't get the question. Surely the focused item is the sole selected item when you use the keyboard? - Mark Bertenshaw

1 Answers

1
votes

Try this instead:

if (e.KeyCode == Keys.Down)
{
    if (listView1.Visible && listView1.Items.Count > 0)
    {
        index = listView1.SelectedIndices[0];  
        index = index - 1;
        this.listView1.Items[index].Selected = true;
    }
}

I think you are getting an IndexOutOfBound because you don't have any items in the list.