简体   繁体   English

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

[英]Reading and displaying data from CSV file on Windows Form Application using C#

I have written the following code for reading data from .csv file: 我已经编写了以下用于从.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)
        {

        }
    }
}

Here is my CSV File data (readCSV.csv): 这是我的CSV文件数据(readCSV.csv):

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

I have a dataGridView in my Windows Form Application (see image link below as I haven't accumulated enough reputation to post an image) and want to display data from CSV file in this grid view. 我的Windows窗体应用程序中有一个dataGridView (请参阅下面的图像链接,因为我没有积累足够的声誉来发布图像),并希望在此网格视图中显示CSV文件中的数据。 This code isn't throwing any error/warning but it is simply not executing the way it should. 此代码不会抛出任何错误/警告,但它根本不执行它应该的方式。 On clicking the Find button the data is not getting displayed in the dataGridView . 单击“查找”按钮时,数据不会显示在dataGridView中 I am using Visual Studio 2013 Professional. 我正在使用Visual Studio 2013 Professional。

WinFormApp

Silly Me: Oops!!! 傻我:哎呀! The above code is working absolutely fine... I was writing my code on Remote machine and I stored my file on local machine. 上面的代码工作得很好......我在远程机器上编写代码,然后将文件存储在本地机器上。 Also, the name of button click event was mistyped. 此外,按钮单击事件的名称输入错误。

NOTE: The answer has been marked as accepted because its logic works too. 注意:答案已标记为已接受,因为其逻辑也有效。 The code written above in my question is also a working absolutely fine 在我的问题上面写的代码也是一个绝对正常的工作

Here is working example to solve your problem.but before you start you should know few things while reading CVS files or excel files. 这是解决问题的工作示例。但在开始之前,您应该在阅读CVS文件或Excel文件时知道一些事情。 For excel file always first row is the name of columns so you do not need to add columns to Data-table manually 对于excel文件,始终第一行是列的名称,因此您无需手动将列添加到Data-table

 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;
            }

First check the autogenerateColumns on dataGridView. 首先检查dataGridView上的autogenerateColumns。 Next check if your datatable is correcting being filled. 接下来检查您的数据表是否正在纠正填充。

Check this example, can help you a lot: Faster way of reading csv to grid 查看这个例子,可以帮到你很多: 更快捷地将csv读取到网格

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

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