使用ComboBox和ListBox中的项目

时间:2011-10-08 15:28:36

标签: c# winforms

我想使用C#2010(表单)在ComboBox和ListBox之间来回移动项目 我的代码似乎工作。但是,当我将项目移回ComboBox(从ListBox)时,我在项目之间有一个空格。如果有人建议如何删除ComboBox中的项目之间的空间,我将非常感激。

private void stateslistcomboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    stateslistBox.Items.Add(statescomboBox.SelectedItem);
    statescomboBox.Items.RemoveAt(statescomboBox.SelectedIndex);
}

private void stateslistBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string item = "";
    item = Convert.ToString(stateslistBox.SelectedItem);
    statescomboBox.Items.Add(item);
    stateslistBox.Items.Remove(stateslistBox.SelectedItem);
}

1 个答案:

答案 0 :(得分:3)

statescomboBox.Items.Add(item);触发另一个SelectIndexChanged添加空项目。

尝试

private void stateslistBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string item = "";
    item = Convert.ToString(stateslistBox.SelectedItem);
    statescombobox.SelectIndexChanged -= stateslistBox_SelectedIndexChanged;
    statescomboBox.Items.Add(item);
    statescombobox.SelectIndexChanged += stateslistBox_SelectedIndexChanged;
    stateslistBox.Items.Remove(stateslistBox.SelectedItem);
}

或者,您可以阻止添加空项目。

private void stateslistBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string item = "";
    item = Convert.ToString(stateslistBox.SelectedItem);
    if (!string.IsNullOrEmpty(item)
    {
        statescomboBox.Items.Add(item);
        stateslistBox.Items.Remove(stateslistBox.SelectedItem);
    }
}