我發現Items.Clear並不總是通過數據源填充列表框時清除列表框。將DataSource設置爲Null可以使用Items.Clear()清除它。爲了更改列表項目,將ListBox的DataSource屬性設置爲null是錯誤的嗎?
這是這樣做的錯誤方式嗎?我的想法有點不對嗎?
謝謝。
下面是我準備說明我的問題的代碼。它包含一個Listbox和三個按鈕。
如果單擊該訂單中的所有一切工作的按鈕:
- 填單子隨着陣列按鈕
- 填充列表項使用數組按鈕
- 填充列表項隨着數據源按鈕
但是,如果先單擊「使用DataSource填充列表項」按鈕,則單擊其他兩個按鈕之一會導致此錯誤:「未處理的類型爲'System.ArgumentE 「System.Windows.Forms.dll中出現xception」,並且「設置DataSource屬性時無法修改Items集合。」
評論?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFillListWithArray_Click(object sender, EventArgs e)
{
string[] myList = new string[4];
myList[0] = "One";
myList[1] = "Two";
myList[2] = "Three";
myList[3] = "Four";
//listBox1.DataSource = null; <= required to clear list
listBox1.Items.Clear();
listBox1.Items.AddRange(myList);
}
private void btnFillListItemsWithList_Click(object sender, EventArgs e)
{
List<string> LStrings = new List<string> { "Lorem", "ipsum", "dolor", "sit" };
//listBox1.DataSource = null; <= required to clear list
listBox1.Items.Clear();
listBox1.Items.AddRange(LStrings.ToArray());
}
private void btnFillListItemsWithDataSource_Click(object sender, EventArgs e)
{
List<string> LWords = new List<string> { "Alpha", "Beta", "Gamma", "Delta" };
//listBox1.DataSource = null; <= required to clear list
listBox1.Items.Clear();
listBox1.DataSource = LWords;
}
}
據微軟稱,你需要設置數據源爲空清除的項目。 http://support.microsoft.com/kb/319927 – 2015-02-23 20:15:42