简体   繁体   English

使用listview项值C#填充文本框

[英]Populating textbox with listview item value C#

I am populating a list-view with passwords. 我用密码填充列表视图。 Then I want to take the selected items text and pass it to a text box when it is clicked. 然后我想获取所选项目文本并在单击时将其传递到文本框。

So far I have: 到目前为止,我有:

 private void passwordListView_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListViewItem listViewItem = new ListViewItem();
        listViewItem = passwordListView.SelectedItems[0];
        passwordTextBox.Text = listViewItem.Text;
    }

It works the first time I press it and it populates the textbox but then if I click a different password in the list-view it throws an exception. 它第一次按下它时工作,它填充文本框,但如果我在列表视图中单击一个不同的密码,它会抛出异常。

Have I left out something blatantly obvious? 我是否遗漏了一些明显的东西?

When the Selected Index is changed in a winforms ListView the first event is for the item that has now been deselected. 在winforms ListView中更改选定索引时,第一个事件是针对现已取消选择的项目。 So at that point SelectedItems is empty. 所以当时SelectedItems是空的。

Check for this through if (passwordListView.SelectedItems.Count == 0) return; 通过if (passwordListView.SelectedItems.Count == 0) return;检查这个if (passwordListView.SelectedItems.Count == 0) return;

After this you will get a second event, which will be for the new selection, and you can act on this. 在此之后,您将获得第二个事件,该事件将用于新选择,您可以对此采取行动。

Btw, you don't need to make a new ListViewItem as you are in your snippet, this will save the extra unnecessary creation: 顺便说一下,你不需要在你的代码片段中创建一个新的ListViewItem,这将节省额外的不必要的创建:

ListViewItem listViewItem = passwordListView.SelectedItems[0];

Maybe you could try this : 也许你可以试试这个:

private void passwordListView_SelectedIndexChanged(object sender, EventArgs e)
{
    if(passwordListView.SelectedItems.Count > 0)
        passwordTextBox.Text = passwordListView.SelectedItems.First().Text;
}

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

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