首页 > 解决方案 > C# - 从 CSV 文件中读取数据并在 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; }
    }
}

我是一名初学者,从上周开始使用 C# 工作。

.csv读取包含简单数字的文件,但其中包含导致错误的空格

System.IndexOutOfRangeException

在此处输入图像描述

标签: c#csvdatagridview

解决方案


以下是该方法的简化非LINQ版本,LoadCSV()它可以帮助您在代码中更好地理解您的场景。方法 -

  1. Product仅当该行具有任何值时才创建
  2. 创建Productwith only 属性A
  3. B仅当第二个值可用时才为属性设置值
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;
}

推荐阅读