Reading from .txt file, then exporting data to DataGridView

后端 未结 1 703
[愿得一人]
[愿得一人] 2020-12-06 08:48

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 anythi

相关标签:
1条回答
  • 2020-12-06 09:23

    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");
    
    0 讨论(0)
提交回复
热议问题