8bitcat
8bitcat

Reputation: 2224

C# programmatically change selected item in listview

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;
    }
}

Upvotes: 0

Views: 19998

Answers (1)

Tomas Jansson
Tomas Jansson

Reputation: 23462

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.

Upvotes: 2

Related Questions