![](/img/trans.png)
[英]listbox error: Items collection cannot be modified when the DataSource property is set
[英]Is it wrong to set ListBox DataSource property to null in order to change list Items?
我发现当列表框已通过数据源填充时,Items.Clear 并不总是清除列表框。 将 DataSource 设置为 Null 允许使用 Items.Clear() 清除它。
这是这样做的错误方法吗? 这样做是不是我的想法有点错误?
谢谢。
下面是我准备用来说明我的问题的代码。 它包括一个列表框和三个按钮。
如果您按此顺序单击按钮,则一切正常:
但是,如果您首先单击“使用数据源填充列表项”按钮,则单击其他两个按钮中的任何一个都会导致此错误:“System.Windows.Forms.dll 中发生类型为‘System.ArgumentException’的未处理异常”,并带有“设置 DataSource 属性后,无法修改项目集合。”
注释?
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;
}
}
根据 Microsoft 的说法,似乎将数据源设置为 Null 然后清除列表是可以接受的。
如果您的列表框绑定到一个数据源,那么该数据源将成为列表框的“主”。 然后您不清除列表框,但您需要清除数据源。 因此,如果列表框绑定到 LWords,则执行 Lwords.clear() 并且列表框将被清除。 这是正确的行为,因为这就是数据绑定的全部内容。
如果您将数据源设置为 null,您基本上是在告诉列表框它不再是数据绑定的。 当然,它的副作用是它变空了。 但是根据情况,您可能不希望只清除列表框,但您可能希望同时清除数据源和列表框。
假设您想通过 GUI 清除 LWords,并且 LWords 是您的列表框的来源,您按下一个按钮并将数据源设置为 null,您看到列表框变空,认为 LWords 不是空的,但 LWords 不是空,然后在这种情况下,这将是一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.