我发现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