0

私はC#winFormでアプリを作成しており、ListViewを使用してデータを保存しています。フォームを閉じたときにこのアイテムのリストを保存し、フォームを再度開いたときに再度ロードする必要があります。

これは、リストに新しい要素を追加するためのコードです。

string[] timeitem = new string[2];

timeitem[0] = txtDescription.Text;
timeitem[1] = msktime.Text;

ListViewItem lvi = new ListViewItem(timeitem);

lstTimes.Items.Add(lvi);

このリストを保存してロードするための最良の方法は何ですか?ユーザーのダイアログは必要ありません。ユーザーがListViewアイテムを含むフォームを開くたびに、このリストが自動的に保存およびロードされる必要があります。私は.txtまたはxmlファイルのいずれかを使用することができます。

4

1 に答える 1

2

You could write a simple helper class for that:

class ListItemsHelper
{
    private const string FILE_NAME = "items.dat";

    public static void SaveData(Items items)
    {
        string data = SerializeItems(items);
        File.WriteAllText(GetFilePath(), data);
    }

    public static Items LoadData()
    {
        string data = File.ReadAllText(GetFilePath());
        return DeserializeItems(data);
    }

    private static string GetFilePath()
    {
        return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILE_NAME);
    }

    private static string SerializeItems(Items items)
    {
        //Do serialization here
    }

    private static Items DeserializeItems(string data)
    {
        //Do deserialization here
    }
}

Use:

ItemsStateHelper.SaveData(items);

Items data = ItemsStateHelper.LoadData();

Additionally, you would have to include some exception handling and choose where you want to save the file. In the code i posted it is saving on folder where the exe file is located.

于 2013-03-04T00:15:06.410 に答える