问题描述
我创建了一个包含以下组件(button1,button2和列表框)的简单项目.
按钮1的代码
I created a simple project with following components (button1, button2 and listbox).
The code for button 1
listBox1.Items.Clear();
RegistryKey OurKey = Registry.LocalMachine;
OurKey = OurKey.OpenSubKey(@"SOFTWARE\\MyRegistry\\", true);
if (OurKey != null)
{
foreach (string sub in OurKey.GetSubKeyNames())
{
listBox1.Items.Add(sub);
}
OurKey = OurKey.OpenSubKey(@"SOFTWARE\\MyRegistry\\", false);
}
else
{
listBox1.Items.Add("Key does not exist");
}
按钮2的代码
The code for button 2
listBox1.Items.Clear();
openFileDialog1.InitialDirectory = @"C:\MyFile\MyFiles";
openFileDialog1.Filter = "text|*.txt|All|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
string[] lines = File.ReadAllLines(openFileDialog1.FileName);
listBox1.DataSource = lines;
}
//listBox1.DataBindings.Clear();
// listbox1.DataSource=null
当我单击按钮1时,将正确填充列表框,然后单击按钮2,列表也将正确填充;当单击按钮2时,列表也将正确填充.但是,如果再次单击按钮1,则会出现错误设置DataSource属性时无法修改项目集合".
我尝试使用"listbox1.DataSource = null"或"listBox1.DataBindings.Clear()",但没有运气
When I click button one, the listbox is populated correctly, then I click button 2, the list is populated correctly as well; however, if I click button 1 again I get an error "Item collection cannot be modified when the DataSource property is set".
I tried to use "listbox1.DataSource=null" or "listBox1.DataBindings.Clear()" but no luck
Any help will be greatly appreciated
推荐答案
List<string> myList = new List<string>();
myList.Add("Item 1");
myList.Add("Item 2");
myList.Add("Item 3");
listBox1.DataSource = myList;</string></string>
这篇关于数据源连接未重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!