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

查看:595
本文介绍了从.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 (用户)的文件中读取数据,并将其粘贴到 DataGridView的表在C#微软的Visual 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.

现在,我有previously创建类用户,它具有以下字段:

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


  • ID

  • 名称


  • 电话

  • VIP

  • 购买的物品

  • 价格

然后创建一个DataGridView( usersDataGridView ),并在其类用户进口等领域。

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

OK,这个算法有些是容易的事,不是吗?

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

我的想法是做了以下内容:阅读与的StreamReader ,节约每行一个字符串,然后分割字符串转换成使用部分 \\ t 与分隔符 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 \t as a delimiter with String.Split.

但是,一旦我得到了那些行拆分......好吧,我基本不知道如何将它们导入到DataGridView的(我知道它应该是作为一个数据源但是......在Visual Studio 2012的UI显得太复杂对我来说,让我找出我怎么可以指向字符串或任何该死的数据类型,它是作为一个DataSource)。

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('\t');

    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('\t'));

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

尝试二:

public void ReadFromFile()
{
    string delimeter = "\t";
    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("\r".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的我想我必须在algorhitmic一级,一些可怕的错误,从字面上没有经验吧?!

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?

任何帮助或答案深感AP preciated !!

Any help or answers are deeply appreciated!!

推荐答案

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

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('\t');
      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天全站免登陆