c# - 使用 C# 在 Windows 窗体应用程序上读取和显示 CSV 文件中的数据

标签 c# winforms csv datagridview

我编写了以下用于从 .csv 文件读取数据的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace CSVRead
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void buttonRead_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Username");
            dataTable.Columns.Add("Password");
            dataTable.Columns.Add("MachineID");
            string filePath = textBox1.Text;
            StreamReader streamReader = new StreamReader(filePath);
            string[] totalData = new string[File.ReadAllLines(filePath).Length];
            totalData = streamReader.ReadLine().Split(',');
            while (!streamReader.EndOfStream)
            {
                totalData = streamReader.ReadLine().Split(',');
                dataTable.Rows.Add(totalData[0], totalData[1], totalData[2]);
            }
            dataGridView1.DataSource = dataTable;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}

这是我的 CSV 文件数据 (readCSV.csv):

Username, Password, MachineID
abc, abc, 123
jkl, jkl, 789
rst, rst, 456

我的Windows 窗体应用程序 中有一个dataGridView(请参阅下面的图片链接,因为我还没有积累足够的声誉来张贴图片)并希望显示来自此 GridView 中的 CSV 文件。这段代码没有抛出任何错误/警告,但它只是没有按应有的方式执行。单击“查找”按钮时,数据未显示在 dataGridView 中。我使用的是 Visual Studio 2013 Professional。

WinFormApp

愚蠢的我:糟糕!!!上面的代码工作得非常好......我在远程机器上编写我的代码并将我的文件存储在本地机器上。此外,按钮点击事件的名称输入错误。

注意:答案已被标记为已接受,因为它的逻辑也有效。我的问题上面写的代码也可以正常工作

最佳答案

这是解决您的问题的工作示例。但是在您开始之前,您应该在阅读 CVS 文件或 excel 文件时了解一些事情。对于 excel 文件,第一行总是列名,因此您无需手动将列添加到数据表

 try
            {
                // your code here 
     string CSVFilePathName = @"path and file name";
                string[] Lines = File.ReadAllLines(CSVFilePathName);
                string[] Fields;
                Fields = Lines[0].Split(new char[] { ',' });
                int Cols = Fields.GetLength(0);
                DataTable dt = new DataTable();
                //1st row must be column names; force lower case to ensure matching later on.
                for (int i = 0; i < Cols; i++)
                    dt.Columns.Add(Fields[i].ToLower(), typeof(string));
                DataRow Row;
                for (int i = 1; i < Lines.GetLength(0); i++)
                {
                    Fields = Lines[i].Split(new char[] { ',' });
                    Row = dt.NewRow();
                    for (int f = 0; f < Cols; f++)
                        Row[f] = Fields[f];
                    dt.Rows.Add(Row);
                }
                dataGridClients.DataSource = dt;  
 }
            catch (Exception ex )
            {
                MessageBox.Show("Error is " + ex.ToString());
                throw;
            }

关于c# - 使用 C# 在 Windows 窗体应用程序上读取和显示 CSV 文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33494332/

相关文章:

c# - 在 C# 中计算文件行数

c# - 向面板添加标签时具有一定的布局

python - 使用Python修改csv中的特定列

c# - Datagridview 中的文本框示例

c# - 如何从这个陌生的域中获取 Cookie?

c# - BlockingCollection<T>.TakeFromAny,用于具有不同泛型类型的集合

C# DataGridView 添加行 - 验证时,我如何知道该行是新行且尚未提交?

c# - 在 C# 中使用 FlowLayoutPanel 创建面包屑导航控件

c# - 使用 fileHelpers 库的 CSV 中的列标题?

mysql加载数据infile它包含比输入列更多的数据