CSV/Text in DataGrid Wpf

后端 未结 2 1537
陌清茗
陌清茗 2020-12-03 09:36

I cannot seem to figure out how to add my CSV File in a DataGrid. Can someone explain me what my approach should be?

Lets say i have a CSV file with the following co

2条回答
  •  忘掉有多难
    2020-12-03 10:02

    Forget DataTable-based stuff. It's horrendous. It is not strongly typed and it forces you to all sorts of "magic-string" based hacks.

    Instead, create a proper strongly-typed Data Model:

    public class Person
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public int Age { get; set; }
    
        public Gender Gender { get; set; }
    }
    
    public enum Gender
    {
        Male,
        Female
    }
    

    Then create a Service that can load Data from the File:

    public static class PersonService
    {
        public static List ReadFile(string filepath)
        {
            var lines = File.ReadAllLines(filepath);
    
            var data = from l in lines.Skip(1)
                       let split = l.Split(';')
                       select new Person
                       {
                           Id = int.Parse(split[0]),
                           Name = split[1],
                           Age = int.Parse(split[2]),
                           Gender = (Gender)Enum.Parse(typeof(Gender), split[3])
                       };
    
            return data.ToList();
        }
    }
    

    And then use that to populate the UI:

    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();
    
            DataContext = PersonService.ReadFile(@"c:\file.csv");
        }
    }
    

    XAML:

    
        
    
    

    Result:

    enter image description here

提交回复
热议问题