从多个ListBox中删除相对于一个ListBox的索引的项目

时间:2014-01-07 13:51:24

标签: c# listbox

我是C#的新手,想要从三个ListBoxes删除一个项目,但与第一个ListBox

的索引相同

在我的情况下,假设我有3个ListBoxes,我将从第一个ListBox获取项目的索引,例如2.现在我想从所有3 ListBoxes 删除索引2处的项目。问题是我已成功从ListBox 1中的所选索引中删除了该项,但未从其他2 ListBoxes我的代码中删除该项:

public static int indextodelete;

private void List1_Click(object sender, EventArgs e)
{
    DialogResult result1 = MessageBox.Show("Are you sure you want to remove \"" + glossarywords.SelectedItem + "\" as a non specific word?", "Domain Expert", MessageBoxButtons.YesNo);

    if ( result1 == DialogResult.Yes )
    {
        indextodelete = List1.Items.IndexOf(List1.SelectedItem.ToString());
        List1.Items.Remove(List1.SelectedItem);
        List2.Items.Remove(indextodelete);
        List3.Items.Remove(indextodelete);
    } 
}

2 个答案:

答案 0 :(得分:3)

你想要

List2.Items.RemoveAt(indextodelete);
List3.Items.RemoveAt(indextodelete);
  

删除集合中指定索引处的项目。

MSDN Documentation for RemoveAt

.Remove()将删除完整对象,而不是索引。 RemoveAt()获取索引。

完全修改的方法:

public static int indextodelete;
private void List1_Click(object sender, EventArgs e)
{
    DialogResult result1 = MessageBox.Show("Are you sure you want to remove \"" + glossarywords.SelectedItem + "\" as a non specific word?", "Domain Expert", MessageBoxButtons.YesNo);

    if (result1 == DialogResult.Yes)
    {
        // remove based on object
        List1.Items.Remove(List1.SelectedItem);

        indextodelete = List1.Items.IndexOf(List1.SelectedItem.ToString());

        // remove based on index.
        List2.Items.RemoveAt(indextodelete);
        List3.Items.RemoveAt(indextodelete);
    }
}

答案 1 :(得分:2)

您需要另外两个列表框的RemoveAt方法:

List1.Items.Remove(List1.SelectedItem);
List2.Items.RemoveAt(indextodelete);
List3.Items.RemoveAt(indextodelete);