我正在尝试从 ComboBox 集合中删除选定的项目:
我写了一个 buttonClick:
cb01.Items.Remove(cb01.SelectedItem);.
这会删除该项目,但下次我打开表单时 - 该项目再次出现。请帮忙。
为您的 ComboBox添加KeyDown
事件,然后
private void cb01_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
if(cb01.SelectedIndex != -1)
cb01.Items.Remove(cb01.SelectedItem);
}
}
以上将从组合框中删除项目,但如果您在再次加载应用程序时在设计时间添加项目,您可以再次看到所有项目。
检查你的InitializeComponent()
方法。你可以看到类似下面的东西。
this.cb01.Items.AddRange(new object[] {
"item1",
"item2",
"item13"});
当您再次加载应用程序时,它将调用InitializeComponent
并调用上述方法来添加项目。
为了避免这个问题。您可以使用绑定数据源。例如,您可以从数据库中获取项目。当您删除时,您可以将其从数据库中删除。下次加载应用程序时,它只显示数据库中的项目。
怎么样
if(cb01.SelectedItem != null)
cb01.Items.Remove(cb01.SelectedItem);
为什么我做检查?
因为在最后一行你说
cb01.Items.RemoveAt(cb01.SelectedIndex); // error: Value of '-1' is not valid...
-1 是未选择任何项目时组合的索引。所以我先检查了选定的项目。如果找到将进入 if 语句。
替换comboBox1
为您的组合框的名称并绑定其KeyDown
事件
void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
int currentItem = comboBox1.SelectedIndex;
if (e.KeyCode == Keys.Delete && currentItem != -1)
{
comboBox1.Items.RemoveAt(currentItem);
if (comboBox1.Items.Count > 0)
comboBox1.SelectedIndex = (currentItem > 0 ? currentItem - 1 : currentItem);
}
}
这将在删除后选择列表中的下一个项目,或者如果组合框中没有项目或未选择任何项目,则不执行任何操作。