I have used
CsvHelper[
^] to parse the CSV file. CSV files are a little tricky and must confirm to the
RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files[
^].
Now, using the CsvHelper, here is one way to dynamically load a WPF Listview creating headers on-the-fly and dynamically loading the data:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadData();
}
List<string[]> items = new();
private void LoadData()
{
MyListView.View = new GridView();
GridView grid = (MyListView.View as GridView)!;
using (var reader = new StreamReader("book1.csv"))
using (var csv = new CsvReader(reader,
CultureInfo.InvariantCulture))
{
csv.Read();
csv.ReadHeader();
for (var index = 0; index < csv.HeaderRecord!.Length; index++)
{
var value = csv.HeaderRecord[index];
grid.Columns.Add(new GridViewColumn()
{
Header = csv.HeaderRecord[index],
DisplayMemberBinding = new Binding($"[{index}]")
});
}
while (csv.Read())
{
int count = csv.Parser.Record!.Length;
string[] item = new string[count];
for (int index = 0; index < count; index++)
{
item[index] = csv.Parser.Record[index];
}
items.Add(item);
}
}
MyListView.ItemsSource = items;
}
}