简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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