CSV/Text in DataGrid Wpf

后端 未结 2 1533
陌清茗
陌清茗 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 09:58

    Although i found some other way: kept it simple

    This is my way i just figured:

    //Location of CSV File
            string CSVDataBase = @"C:\CSVDatabase.csv";
    
            //Create Collection for DataGrid Source
            ICollection CreateDataSource()
            {
                //Create new DataTables and Rows
                DataTable dt = new DataTable();
                DataRow dr;
    
                //Create Column Headers
                dt.Columns.Add(new DataColumn("ID", typeof(string)));
                dt.Columns.Add(new DataColumn("Name", typeof(string)));
                dt.Columns.Add(new DataColumn("Age", typeof(string)));
                dt.Columns.Add(new DataColumn("Gender", typeof(string)));
    
    
                //For each line in the File
                foreach (string Line in File.ReadLines(CSVDataBase))
                {
                    //Split lines at delimiter ';''
    
                    //Create new Row
                    dr = dt.NewRow();
    
                    //ID=
                    dr[0] = Line.Split(';').ElementAt(0);
    
                    //Name =
                    dr[1] = Line.Split(';').ElementAt(1);
    
                    //Age=
                    dr[2] = Line.Split(';').ElementAt(2);
    
                    //Gender= 
                    dr[3] = Line.Split(';').ElementAt(3);
    
                    //Add the row we created
                    dt.Rows.Add(dr);
                }
    
                //Return Dataview 
                DataView dv = new DataView(dt);
                return dv;
            }
    

    Then all i had to do is:

    public void loadDataGridView()
    {
      //Load everything in datagrid
      myDataGrid.ItemsSource = CreateDataSource();
    }
    

    Thats it! is this a good approach? Anyway Thanks for the help.

提交回复
热议问题