2015-04-06 87 views
0

我正在使用BindingList作爲我的ListBox的數據源。從ListBox中刪除項目時C#程序崩潰

public static BindingList<memo> memosList = new BindingList<memo>(); 

每當我嘗試刪除選定的對象(通過按鈕),我的程序崩潰。

private void editMemo_Click(object sender, EventArgs e) 
    { 
     listBox1.Items.Remove(listBox1.SelectedItem); 
    } 

我得到以下錯誤:

An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll

Additional information: Items collection cannot be modified when the DataSource property is set.

我也曾嘗試使用:

private void editMemo_Click(object sender, EventArgs e) 
    { 
     Form2.memosList.Remove(listBox1.SelectedIndex); 
    } 

但是這不會讓我編譯。

如何在不拋出異常的情況下移除物品?

+0

你想將數據讀入一個列表,然後有一個綁定到列表框中該名單?現在你正試圖從列表框(和數據源)中刪除。第二個是 – Mathemats

+0

,如果你指定一個索引,你想'RemoveAt',我想。 –

回答

2

您應該從的BindingList刪除項目你已經綁定到你的列表中的數據源

private void editMemo_Click(object sender, EventArgs e) 
{ 
    if(listBox1.SelectedItem != null) 
    { 
     BindingList<memo> bl = listBox1.DataSource as BindingList<memo>; 
     bl.Remove(listBox1.SelectedItem as memo) ; 
    } 
} 
+0

我有一個方法,當單擊列表框中的項目時,在標籤中顯示整個對象; ____________________________________________________________________________________ private void listBox1_SelectedIndexChanged(object sender,EventArgs e) { 備忘錄備忘錄=(備忘錄)listBox1.SelectedItem; lblTitle.Text = memo.memoTitle.ToString(); lblPriority.Text = memo.memoPriority.ToString(); lblDescription.Text = memo.memoDescription.ToString(); } 這個仍然會拋出該項目被刪除時的錯誤:S – Willi4m

+0

http://www.codeshare.io/qH0ml我已經添加了這段代碼給代碼共享,所以它更容易閱讀xD如果我刪除代碼來顯示在標籤中的項目細節,它工作正常,但否則所有3都會拋出異常。 – Willi4m

+0

什麼例外?空引用異常?當你刪除一個項目時,選中的項目被重置,可能是SelectedIndexChanged沒有任何SelectedItem。添加'if(!listBox.SelectedItem == null){用selecteditem填充標籤} else {清除標籤}' – Steve