2014-09-25 168 views
0

基本上它是一個聯繫人列表,從列表框中選擇聯繫人並點擊刪除按鈕,從列表中刪除它。刪除列表中的選定項目

 private void btnRmv_Click(object sender, EventArgs e) 
    { 

     try{ 

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

     people.RemoveAt(listBox.SelectedIndex); 

     } 
     catch { } 
    } 

此代碼似乎刪除列表框中的聯繫人,但如果我保存我的程序並再次打開它,聯繫人就回到那裏。我將所有聯繫人保存在Xml文件中。該程序自動保存退出,並有一個手動保存按鈕。

感謝

+1

從人刪除首先列出?由於SelectedIndex將在您從列表框中刪除SelectedItems時發生變化。 – Adassko 2014-09-25 07:51:35

+0

哦,我的。這總是你錯過的最簡單的事情。謝謝 – CodingNub 2014-09-25 07:56:28

回答

1

你不顯示在您的代碼是爲了節省,但我想有一個接觸失蹤 - 也許你想刪除的聯繫人下一個?

由於您在使用SelectedIndex從列表框中刪除項目後,必須選擇其他項目。

嘗試扭轉順序:

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

嘗試從「人」先刪除,然後從列表框中刪除它,否則對選定的指標參數。示例代碼粘貼下面

try 
    { 

    int _SeletedIndex = listBox.SelectedIndex(); 

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

    people.RemoveAt(_SeletedIndex); 

    } 
    catch { } 
1

您要刪除selected item首先,讓你失去了選擇的指數,沒有項目在列表people刪除。

讓我們重新安排線路:

people.RemoveAt(listBox.SelectedIndex); 

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