【问题标题】:Having an evolutive list of stored data, without database拥有不断发展的存储数据列表,无需数据库
【发布时间】:2014-07-03 09:16:00
【问题描述】:

我正在做一个识别车辆的 winforms 应用程序。

在这个应用程序中,我将使用与车辆相对应的识别码。

很简单,我一年内所有汽车只有一个代码,一年内自行车只有一个代码。

所以,我在考虑这种数据::

year | car code | bike code
2014 | 156 | 185
2015 | 158 | 189

我有一个子表单,它将所有这些数据显示到一个列表框(或其他列表类型)中,并且允许我添加一行。当我添加一行时,我会显示在列表中,并且会被添加到文件中。

在另一个视图中,我会将所有“年份”部分显示到一个组合框中。

我想知道的是,将数据存储到文件(csv、xml 或其他...)中的最佳方式是什么,以便我可以轻松读取和编辑此文件,并将数据显示为

我知道如何使用数据库,但是没有数据库,我从来没有做过,也找不到任何可以帮助我的东西。

我希望我很清楚,如果没有,请告诉我。

编辑:

public FormPref()
        {

            lst = GetIdentifiant(path);
            dataGridViewIdentifiant.DataSource = lst;
}

private void buttonAddIdentifiant_Click(object sender, EventArgs e)
        {
            Vehicule identifiant = new Vehicule();
            if (!string.IsNullOrEmpty(textBoxYear .Text) &&
                !string.IsNullOrEmpty(textBoxCarCode .Text) &&
                !string.IsNullOrEmpty(textBoxBikeCode .Text))
            {
                identifiant.Year = textBoxYear .Text;
                identifiant.CarCode = textBoxCarCode .Text;
                identifiant.BikeCode = textBoxBikeCode .Text;
                lst.Add(identifiant); 
            }
        }

我尝试通过刷新、更新来更新 datagridview 中的显示,但没有任何效果。

datagridview 与类的值绑定。

谢谢。

【问题讨论】:

标签: c# winforms


【解决方案1】:

如果您没有大量数据,可以将其存储在 csv 文件中。 添加新值时,您可以使用 File.AppendAllLines 来避免重写文件

又快又脏

public class Vehicule
{
    public int Year { get; set; }
    public int CarCode { get; set; }
    public int BikeCode { get; set; }

    public override string ToString()
    {
        return string.Format("{0},{1},{2}", Year, CarCode, BikeCode);
    }
}

public class FileStorage
{
    public List<Vehicule> GetVehicules(string filePath)
    {
        return File.ReadAllLines(filePath).Select(s => s.Split(',')).Select(split => new Vehicule
        {
            Year = int.Parse(split[0]),
            CarCode = int.Parse(split[1]),
            BikeCode = int.Parse(split[2])
        }).ToList();
    }

    public void WriteVehicules(string filePath, IEnumerable<Vehicule> vehicules)
    {
        File.WriteAllLines(filePath, vehicules.Select(s => s.ToString()));
    }
}

还有非常好的 nuget 包可以轻松操作 CSV ;)

【讨论】:

  • 谢谢,这行得通。而且确实不会有很多数据,每年只增加一条。
猜你喜欢
  • 2012-09-02
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
  • 2016-11-27
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多