Home > OS >  Read CSV column values based on column header name in C#
Read CSV column values based on column header name in C#

Time:09-12

Could anyone please tell me how to read column data from a csv file ? This csv file has column headers and column values for each work sheet.

In my WPF window, I have 2 list boxes. First list box (lst1) is populated with Column header names. I want to load 2nd list box (lst2) with column values of selected item (column header names) in the first list box.

Here is the code I used for loading column header names in the first list box.

    public List<string> ColumnNameGenerator(string FilePath)
    {
        string firstLine = "";
        using (StreamReader reader = new StreamReader(FilePath))
        {
            firstLine = reader.ReadLine() ?? "";
        }
        return firstLine.Split(',').ToList();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string path = "D:\\Tutorial\\ExcelDocs\\school.csv";
        lst1.ItemsSource = ColumnNameGenerator(path);            
    }

And I tried something like to get the column values when we select a header value in the 1st list box.

    private void lst1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var csv = from line in lst1.SelectedItem as List<string>
                  select (line.Split(',')).ToArray();
        lst2.ItemsSource = csv;
    }

But it is not working. How it can be done ?

Thanks in advance.

CodePudding user response:

I found out a solution for this issue. I used CsvHelper to solve it.

  private void lst1_SelectionChanged(object sender, 
                                    SelectionChangedEventArgs e)
    {
        lst2.Items.Clear();

        string columnheadername = lst1.SelectedItems[0].ToString();

        CsvConfiguration csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            HasHeaderRecord = true,
            Delimiter = ","
        };

        CsvReader csv = new CsvReader(File.OpenText(path), csvConfiguration);
        csv.Read();
        csv.ReadHeader();

        while (csv.Read())
        {               
            var stringField = csv.GetField<string>(columnheadername);
            lst2.Items.Add(stringField);
        }            
    }
  • Related