繁体   English   中英

C# - 从 CSV 文件中读取数据并在 DataGridView 中显示它们

[英]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; }
    }
}

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

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

System.IndexOutOfRangeException

在此处输入图像描述

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

  1. 仅当该行具有任何值时才创建Product
  2. 创建仅具有属性AProduct
  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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM