简体   繁体   English

停止按钮导致列表框取消选择

[英]Stop Button Causing ListBox to Deselect

I have a button in place so that when I click it, it deletes the selected ListItem from the ListBox called listBoxNames and removes the selected Person object from a list named people . 我有一个按钮,当我单击它时,它从名为listBoxNamesListBox listBoxNames删除选定的ListItem ,并从名为people的列表中删除选定的Person对象。

However, after clicking the delete button an error message pops up telling me that the index is out of range. 但是,单击删除按钮后,弹出错误消息,告诉我索引超出范围。 This leads me to believe that upon clicking the button, it has deselected the ListBox and so listBoxNames.SelectedIndex returns -1. 这使我相信,单击按钮后,它已取消选择ListBox ,因此listBoxNames.SelectedIndex返回-1。

Is there anyway around this or have I made some stupid mistake? 无论如何还是我犯了一些愚蠢的错误?

private void deleteEntryBtn_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            listBoxNames.Items.Remove(listBoxNames.SelectedItems[0]);
            people.RemoveAt(listBoxNames.SelectedIndex);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Your code removes the selected item. 您的代码将删除所选项目。
Once that item isn't there, there is no selection. 一旦该项目不存在,就没有选择。

You need to check which item is selected before removing it. 您需要先检查选择了哪个项目,然后再将其删除。

Try this instead: 尝试以下方法:

private void deleteEntryBtn_Click(object sender, RoutedEventArgs e)
{
    try
    {
        people.RemoveAt(listBoxNames.SelectedIndex);
        listBoxNames.RemoveAt(listBoxNames.SelectedIndex);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

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

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