修改listBox中的数据并将其保存到文本文件中

问题描述 投票:1回答:1

我正在使用c#Windows Forms Application开发系统。我将一个文本文件导入listbox1,然后将listbox1中的数据传递给第二个Windows窗体的listbox2。在第二个Windows窗体中,我需要更改数据并将更改后的数据保存到新的文本文件中。

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9PYktLci5wbmcifQ==” alt =“在此处输入图像描述”>

具有以下形式的4个按钮,其中Add按钮用于添加数据的新行,Update按钮可以修改原始数据,Remove按钮可以删除整行选择的数据和保存按钮用于将列表框2中的数据保存到新的文本文件中。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
public partial class Form2 : Form
{
    public Form2(ListBox.ObjectCollection items)
    {
        InitializeComponent();
        listBox2.Items.AddRange(items);
    }

    private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        const string sPath = "save.txt";

        System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
        foreach (var item in listBox2.Items)
        {
            SaveFile.WriteLine(item.ToString());
        }
        MessageBox.Show("Text file saved!");
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {

    }

    private void btnRemove_Click(object sender, EventArgs e)
    {

    }
}
}

任何人都可以提出有关如何执行此操作的建议吗?现在,我已经可以在第二个Windows窗体中将数据从listbox1传递到listbox2了。谢谢。

c# listbox edit
1个回答
0
投票

您可以像这样简单地完成它:

File.WriteAllLines("save.txt", listBox2.Items.Cast<string>().ToArray());
© www.soinside.com 2019 - 2024. All rights reserved.