Deckster711 Deckster711 - 1 month ago 7x
C# Question

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. So at that point SelectedItems is empty.

Check for this through 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 = passwordListView.SelectedItems[0];