sablemarten
sablemarten

Reputation: 1

C# - Reading data from CSV file and show them in DataGridView

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    
    private void btnLoad_Click(object sender, EventArgs e)
    {
        dgvData.DataSource = LoadCSV(@"C:\working\Summary.csv");
    }
    
    public List<Product> LoadCSV(string csvFile)
    {
        var query = from line in File.ReadAllLines(csvFile)
                    let data = line.Split(',')
                    select new Product
                    {
                        A = data[0],
                        B = data[1]
                    };
                    
        return query.ToList();
    }

    public class Product
    {
        public string A { get; set; }
        public string B { get; set; }
    }
}

I am a beginner who started using C# from last week for work.

.csv file containing simple numbers is read, but it is containing spaces which result in an error

System.IndexOutOfRangeException

enter image description here

Upvotes: 0

Views: 82

Answers (1)

atiyar
atiyar

Reputation: 8315

Following is a simplified, non-LINQ version of the LoadCSV() method which might help you understand your scenario better in code. The method -

  1. creates a Product only if the line has any value
  2. creates the Product with only property A
  3. sets a value for property B only if the second value is available
public List<Product> LoadCSV(string csvFile)
{
    // create an empty list
    var list = new List<Product>();

    // read all the lines
    var lines = File.ReadAllLines(csvFile);
    
    // do some processing for each line
    foreach (var line in lines)
    {
        // split line based on comma, only if line is not an empty string
        // if line is an empty string, skip processing
        var data = line.Split(',', StringSplitOptions.RemoveEmptyEntries);      
        if (data.Length == 0)
            continue;

        // we skipped empty lines, so data has at least one element
        // we can safely create a Product with the first element for property A
        var product = new Product { A = data[0] };
        
        // if data has more than one element, then we have a second element
        // we can safely assign the second element to property B 
        if (data.Length > 1)
        {
            product.B = data[1];
        }
        
        // add the product to list
        list.Add(product);
    }
    return list;
}

Upvotes: 1

Related Questions