简体   繁体   English

C#以编程方式更改ListView中的选定项目

[英]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. 我已将keydown绑定到文本框。 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. 但这不是重点,这就是为什么我将keydown事件绑定到文本框以便能够更改listview中的selecteditem的原因。

the code that visuaö studio is complaining about is this visuaöstudio抱怨的代码是这个

index = listView1.SelectedIndices[0];

the zero is somehow wrong? 零是怎么回事?

I'm using a listview ! 我正在使用列表视图

How do I change the listview selecteditem programatically? 如何以编程方式更改listview selecteditem 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. 值0对索引无效。 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;
    }
}

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. 我认为您正在获取IndexOutOfBound因为列表中没有任何项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM