mdanishs
mdanishs

Reputation: 2036

selecting an item from listview in C#

I am trying to show the selected item in listview in a message box, so using the following code

    private void lstMovie_SelectedIndexChanged(object sender, EventArgs e)
    { MessageBox.Show(lstMovie.FocusedItem.Text);}

it works fine for the first time but second time I try to select another item it throws an exception. Object reference not set to an instance of an object.

Upvotes: 1

Views: 1192

Answers (2)

Adriaan Stander
Adriaan Stander

Reputation: 166336

Maybe you should rather be using ListView.SelectedItems Property instead of ListView.FocusedItem Property

ListView.FocusedItem Property

Although an item may be the one displaying the focus reticle, it may not actually be a selected item in the ListView. Use the SelectedItems or SelectedIndices properties to obtain the selected items in the ListView control, the FocusedItem property is not necessarily selected.

Upvotes: 1

DelegateX
DelegateX

Reputation: 719

Try this:

private void lstMovie_SelectedIndexChanged(object sender, EventArgs e)
{
  if(lstMovie.SelectedItems.Count > 0)
  MessageBox.Show(lstMovie.SelectedItems[0]); //Will select first selected item.
}

Upvotes: 3

Related Questions