从 .txt 文件中读取,然后将数据导出到 DataGridView [英] Reading from .txt file, then exporting data to DataGridView

查看:16
本文介绍了从 .txt 文件中读取,然后将数据导出到 DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个可笑的问题,但是上帝啊,我在最后一天都在用它来敲打我的头,但它根本行不通!该死的老师甚至没有提到任何数据导入DataGridView!

I know this is a laughable question, but God, I've spent my entire last day banging my head with it and it just won't work! The goddamn teacher didn't even mention anything about importing any data into DataGridView!

我有一个 C# Windows 窗体作业:我必须从 .txt(用户)文件中读取数据并将其粘贴到 C# Microsoft Visual 中的 DataGridView 表中Studio 2012.users.txt 文件中的数据类似于带有 TAB 分隔符的数据:

I have a C# Windows Forms homework assignment: I have to read data from a .txt (users) file and paste it into a DataGridView table in C# Microsoft Visual Studio 2012. The data in the users.txt file is something like that with TAB delimiters:

-------------------------------------------------
    ID    Name  Surname Telephone VIP Age Balance
-------------------------------------------------
    0001  John  Killer  1-500-300  0  13  2272
    0002  Name  Surname 1-500-200  0  27  225
    0003  Martin King   1-500-400  1  41  1070

忽略标签名称(ID、姓名、姓氏...),我写它们只是为了清楚起见,真实文件中只有原始用户数据.

Ignore the label names (ID, Name, Surname...), I wrote them only for clarity, the real file has only the raw user data in it.

现在,我之前创建了一个 Users 类,其中包含以下字段:

Now, I have previously created a class Users, which has these fields:

  • 身份证
  • 姓名
  • 姓氏
  • 电话
  • 贵宾
  • 购买商品
  • 价格

然后创建一个 DataGridView (usersDataGridView) 并从其中导入类 Users 的字段.

and then created a DataGridView (usersDataGridView) and imported the fields from class Users in it.

好的,从算法上来说,这有点容易,不是吗?

OK, algorithmically this is somewhat easy task, ain't it?

我的想法是执行以下操作:使用 StreamReader 读取文件内容,将每一行保存为一个字符串,然后使用 作为一个字符串将字符串拆分为多个部分带有 String.Split 的分隔符.

My idea was doing the following: reading the file content with a StreamReader, saving each line to a string, then splitting the string into parts using as a delimiter with String.Split.

但是,一旦我将这些行拆分...好吧,我基本上不知道如何将它们导入 DataGridView(我知道"它应该作为 DataSource 但是...Visual Studio 2012 的 UI 对我来说似乎太复杂"了,无法让我弄清楚如何将字符串或任何该死的数据类型指向为数据源).

However, once I got those lines split... well, I basically have no idea how to import them into the DataGridView (I "know" it should be as a DataSource but... the Visual Studio 2012's UI seems way too "complicated" for me to let me figure out how I can point a string or whatever goddamn data type it is as a DataSource).

我可怜的尝试使我想到了以下几点:

My pitiful attempts had led me to the following:

尝试 1:

public void Test_1()
{
    string filePath = string.Format("{0}/databases/{1}", AppDomain.CurrentDomain.BaseDirectory, "user_db.txt");

    string[] textData = System.IO.File.ReadAllLines(filePath);
    string[] headers = textData[0].Split('	');

    DataTable dataTable1 = new DataTable();

    foreach (string header in headers)
        dataTable1.Columns.Add(header, typeof(string), null);

    for (int i = 1; i < textData.Length; i++)
        dataTable1.Rows.Add(textData[i].Split('	'));

    //Set the DataSource of DataGridView to the DataTable
    promotionsDataGridView.DataSource = dataTable1;
}

尝试 2:

public void ReadFromFile()
{
    string delimeter = "	";
    string tableName = "BooksTable";
    string fileName = string.Format("{0}/databases/{1}", AppDomain.CurrentDomain.BaseDirectory, "bigtest.sql");

    DataSet dataset = new DataSet();
    StreamReader sr = new StreamReader(fileName);

    dataset.Tables.Add(tableName);
    dataset.Tables[tableName].Columns.Add("InventoryID");
    dataset.Tables[tableName].Columns.Add("Brand");
    dataset.Tables[tableName].Columns.Add("Category");
    dataset.Tables[tableName].Columns.Add("Description");
    dataset.Tables[tableName].Columns.Add("Promotions");
    dataset.Tables[tableName].Columns.Add("Quantity");
    dataset.Tables[tableName].Columns.Add("Price");

    string allData = sr.ReadToEnd();
    string[] rows = allData.Split("
".ToCharArray());

    foreach (string r in rows)
    {
        string[] items = r.Split(delimeter.ToCharArray());
        dataset.Tables[tableName].Rows.Add(items);
    }
    this.productsDataGridView.DataSource = dataset.Tables[0].DefaultView;
}

但是我不断收到一些废话错误,例如

However I keep getting some bullshit error like

输入数组的大小比任何东西都大

Input array size is bigger than the whatever

因为我几乎没有使用 DataGridView 的经验,所以我想我在算法级别上犯了一些可怕的错误,对吧?!

Since I have literally no experience with DataGridView I guess I have some terrible mistakes at algorhitmic level, right?!

请任何人帮助我!我已经阅读、复制、粘贴、编译和调试了大约 20 个关于类似主题的不同问题,但我仍然无处可去!

Please, anyone, help me! I have read, copied, pasted, compiled and debugged from like 20 different issues on similar topic and I am still at nowhere!

.txt 文件读取数据,然后将其粘贴到 DataGridView 的正确方式是什么?

What's the proper way of reading data from a .txt file, then pasting it to a DataGridView?

非常感谢任何帮助或答案!!

Any help or answers are deeply appreciated!!

推荐答案

如果您已经定义了一个 User 对象,您可以向它添加一个静态方法,将数据加载到用户列表并将其绑定到网格视图.

If you already have a User object defined you can add a static method to it that loads the data to a list of users and bind it to the grid view.

public class User {
  public string Id { get; set; }
  public string Name { get; set; }
  public string Surname { get; set; }
  public string Telephone { get; set; }
  public bool Vip { get; set; }
  public int Age { get; set; }
  public decimal Balance { get; set; }

  public static List<User> LoadUserListFromFile(string path) {
    var users = new List<User>();

    foreach (var line in File.ReadAllLines(path)) {
      var columns = line.Split('	');
      users.Add(new User {
        Id = columns[0],
        Name = columns[1],
        Surname = columns[2],
        Telephone = columns[3],
        Vip = columns[4] == "1",
        Age = Convert.ToInt32(columns[5]),
        Balance = Convert.ToDecimal(columns[6])
      });
    }

    return users;
  }
}

然后您可以简单地将其加载到数据网格中:

Then you can simply load that into a data grid:

usersDataGridView.DataSource = User.LoadUserListFromFile("user_db.txt");

这篇关于从 .txt 文件中读取,然后将数据导出到 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆