簡體   English   中英

從列表中刪除所選項目

[英]Removing the selected Item from the list

基本上,這是一個聯系人列表,從列表框中選擇聯系人,然后單擊“刪除”按鈕,將其從列表中刪除。

        private void btnRmv_Click(object sender, EventArgs e)
    {

        try{

        listBox.Items.Remove(listBox.SelectedItems[0]);

        people.RemoveAt(listBox.SelectedIndex);

        }
        catch { }
    }

這段代碼似乎從列表框中刪除了聯系人,但是如果我保存程序並再次打開它,則聯系人又回到了那里。 我將所有聯系人保存在Xml文件中。 該程序在退出時自動保存,並且具有手動保存按鈕。

謝謝

嘗試先從“人員”中刪除,然后從列表框中刪除它,否則將所選索引作為參數。 示例代碼粘貼在下面

    try
    {

    int _SeletedIndex = listBox.SelectedIndex();

    listBox.Items.Remove(listBox.SelectedItems[0]);

    people.RemoveAt(_SeletedIndex);

    }
    catch { }

您沒有顯示代碼的保存位置,但我想缺少一個聯系人-可能是您要刪除的聯系人下面的那個聯系人?

由於使用的是SelectedIndex之后從列表框中刪除該項目,因此必須選擇其他一些項目。

嘗試顛倒順序:

private void btnRmv_Click(object sender, EventArgs e)
{
    try
    {
        people.RemoveAt(listBox.SelectedIndex);
        listBox.Items.Remove(listBox.SelectedItems[0]);
    }
    catch { }
}

首先要刪除selected item ,所以丟失選定的索引,並且列表people沒有任何項目被刪除。

讓我們重新排列行:

people.RemoveAt(listBox.SelectedIndex);

listBox.Items.Remove(listBox.SelectedItems[0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM