我正在用列表填充listbox1。数据可以发送到第二个列表框2,然后返回。
如何保存属性设置?当您尝试代码时,会出现以下错误:
System.ArgumentException:'设置了DataSource属性后,无法修改项目集合。'
它与listbox1.items.clear();有关。正确的设置方法是什么?
public partial class Form1 : Form
{
List<string> l2;
string selectedItemText;
int SelectedIndex;
public Form1()
{
InitializeComponent();
l2 = new List<string>();
l2.Add("1");
l2.Add("2");
l2.Add("3");
l2.Add("4");
l2.Add("5");
listBox1.DataSource = l2;
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Clear();
foreach (object item in Properties.Settings.Default.listSave)
{
listBox1.Items.Add(item);
}
listBox2.Items.Clear();
foreach (object item in Properties.Settings.Default.listSave2)
{
listBox2.Items.Add(item);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
Properties.Settings.Default.listSave.Clear();
Properties.Settings.Default.listSave2.Clear();
foreach (object item in listBox1.Items)
{
Properties.Settings.Default.listSave.Add(item.ToString());
}
foreach (object item in listBox2.Items)
{
Properties.Settings.Default.listSave2.Add(item.ToString());
}
Properties.Settings.Default.Save();
}
private void button2_Click_1(object sender, EventArgs e)
{
selectedItemText = listBox1.SelectedItem.ToString();
SelectedIndex = listBox1.SelectedIndex;
listBox2.Items.Add(selectedItemText);
if (l2 != null)
{
l2.RemoveAt(SelectedIndex);
}
DataBindings();
}
private void DataBindings()
{
listBox1.DataSource = null;
listBox1.DataSource = l2;
}
private void button4_Click(object sender, EventArgs e)
{
selectedItemText = listBox2.SelectedItem.ToString();
SelectedIndex = listBox2.SelectedIndex;
l2.Add(selectedItemText);
listBox2.Items.RemoveAt(listBox2.Items.IndexOf(listBox2.SelectedItem));
DataBindings();
}
}