为什么列表框行中的单词不仅删除了一行而是删除了2行?

时间:2015-08-19 00:22:02

标签: c#

我启动程序,在列表框中添加一些单词并尝试将其删除。如果所选项目是最后一项,那么它可以正常工作,但如果我在中间选择一个单词,那么它将删除所选单词。然后我再次加载了列表框,最后一个字在某处消失了。任何解决方案?

    public List<string> words = new List<string>();

    public Form2()
    {
        InitializeComponent();
        Load();

        listBox1.DataSource = words;

    }        
    public void Save()
    {
        const string sPath = "Data.txt";
        System.IO.StreamWriter sw = new System.IO.StreamWriter(sPath);
        foreach (string item in words)
        {
            sw.WriteLine(item);
        }

        sw.Close();
    }
    private void Load()
    {
        string line;
        var file = new System.IO.StreamReader("Data.txt");
        while ((line = file.ReadLine()) != null)
        {
            words.Add(line);
        }
    }
    // This Part ???
    private void Remove()
    {
        string contents = null;
        List<string> itemAll = new List<string>();
        foreach (string str in words)
        {
            itemAll.Add(str);
        }
        foreach (string lstitem in listBox1.SelectedItems)
        {
            itemAll.Remove(lstitem);
            //File.AppendAllText(strFile + "Currently In.txt", strName + Environment.NewLine);
        }
        foreach (string s in itemAll)
        { contents += s + Environment.NewLine; }
        System.IO.File.WriteAllText(@"Data.txt", contents);

    }
    private void button2_Click(object sender, EventArgs e)
    {
        // The Remove button was clicked.
        int selectedIndex = listBox1.SelectedIndex;

        try
        {
            // Remove the item in the List.
            words.RemoveAt(selectedIndex);
        }
        catch
        {
        }

        listBox1.DataSource = null;
        listBox1.DataSource = words;
        Remove();

    }

1 个答案:

答案 0 :(得分:0)

由于代码中的words是所有函数的全局变量,因此当您调用它时,您尝试删除项目两次:

words.RemoveAtitemAll.Remove

为了防止它,您可以将其重命名为Remove(),而不是调用UpdateListBox()方法,将这些字词作为参数传递,如:

private void UpdateListBox(List<string> words)
{
    string contents = null;
    List<string> itemAll = new List<string>();
    foreach (string str in words)
    {
        itemAll.Add(str);
    }
}

然后你将有一个单独的方法来保存:

private void Save(List<string> words)
{
    StringBuilder contents = new StringBuilder();
    foreach (string s in words)
    {
        contents.AppendLine(s);
    }
    System.IO.File.WriteAllText(@"Data.txt", contents);
}

然后你会称之为:

private void button2_Click(object sender, EventArgs e)
{
    // The Remove button was clicked.
    int selectedIndex = listBox1.SelectedIndex;

    try
    {
        // Remove the item in the List.
        words.RemoveAt(selectedIndex); //Remove item from words
        UpdateListBox(words); //Update contents on GUI
        Save(words); //Save on IO
    }
    catch
    {
    }
}

我刚刚在这里创建它并且没有在我的IDE上测试它,但你可能知道它是如何工作的。