Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - Reading from .txt file, then exporting data to 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!

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

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

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

  • ID
  • Name
  • Surname
  • Telephone
  • VIP
  • Bought items
  • Price

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?

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.

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:

Attempt 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;
}

Attempt 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

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

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!

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!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...