目前正在使用Winforms并尝试编辑列表框中的项目来上下移动,我在这里遵循了一些指南,我一直收到错误 设置DataSource属性时,无法修改项目集合。'
这是我的代码。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
//Add button was clicked
x = x + 1;
_items.Add("New item " + x);
//Change the data source
listBox1.DataSource = null;
listBox1.DataSource = _items;
}
private void button3_Click(object sender, EventArgs e)
{
//The remove button
int selectedIndex = listBox1.SelectedIndex;
try
{
//Removes the item in the list
_items.RemoveAt(selectedIndex);
x = x - 1;
}
catch
{
}
listBox1.DataSource = null;
listBox1.DataSource = _items;
}
private void button4_Click(object sender, EventArgs e)
{
x = 0;
_items.Clear();
listBox1.DataSource = null;
listBox1.DataSource = _items;
}
private void button5_Click(object sender, EventArgs e)
{
MoveUp();
}
private void button6_Click(object sender, EventArgs e)
{
MoveDown();
}
public void MoveUp()
{
MoveItem(-1);
}
public void MoveDown()
{
MoveItem(1);
}
public void MoveItem(int direction)
{
//Checking selected item
if (listBox1.SelectedItem == null || listBox1.SelectedIndex < 0)
return;//No selected item, nothing will happen
//Calculating new index using move direction
int newIndex = listBox1.SelectedIndex + direction;
//Checking bounds of th range
if (newIndex < 0 || newIndex >= listBox1.Items.Count)
return; //Index out of range - nothing will happen
object selected = listBox1.SelectedItem;
//Removing removable element
listBox1.Items.Remove(selected);
//Insert it into new position
listBox1.Items.Insert(newIndex, selected);
//restore selection
listBox1.SetSelected(newIndex, true);
}
}
}
答案 0 :(得分:1)
当控件绑定到数据源时,无法删除或添加项目。
出于您的目的,您可能应该完全避免使用DataBind
,而只是复制这样的数据:
foreach (var item in _items)
{
myListBox.Items.Add(item);
}