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

C# 使用C在Windows窗体应用程序上读取和显示CSV文件中的数据#,c#,winforms,csv,datagridview,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

我编写了以下代码,用于从.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):

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

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


注意:答案已标记为已接受,因为其逻辑也适用。在我的问题中,上面所写的代码也是一个非常好的工作示例

这里是解决您的问题的工作示例。但是在开始之前,在阅读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;
            }
试试看
{
//你的代码在这里
字符串CSVFilePathName=@“路径和文件名”;
string[]Lines=File.ReadAllLines(CSVFilePathName);
字符串[]字段;
字段=行[0]。拆分(新字符[]{',});
int Cols=Fields.GetLength(0);
DataTable dt=新的DataTable();
//第一行必须是列名;强制使用小写以确保以后匹配。
for(int i=0;i
首先检查dataGridView上的autogenerateColumns。下一步检查数据表是否正在填充

查看此示例,可以为您提供很多帮助:

您是否正在检查DataGridView上的autogeneratecolumns?到目前为止,我还没有检查它
文件。ReadAllLines
将把文件读入一个可枚举文件,所以你可以做一些类似
var contents=File.ReallAllLines(path)
的事情,去掉流读取器,然后循环
内容
并在那里拆分行。你调试并发现任何问题了吗?您可能需要在末尾添加一个
dataGridView1.DataBind()
。CSV文件比这更复杂,例如,如果逗号在引号中怎么办?这对dataGridView没有任何影响(但没有得到任何错误消息或警告),请更改datagrid名称以跟随DG名称。我已经测试了这段代码,结果很好。关于显示错误添加,请尝试捕获您的代码,异常我的datagrid名称与“属性”窗口中显示的名称相同。你能帮助我使用Try-catch代码吗?下面是如何使用Try-catch的示例Try{//your code here}catch(Exception ex){MessageBox.Show(“错误为”+ex.ToString());throw;}///请检查代码,已经用try-catch更新了,我将您的答案标记为已接受,因为您的逻辑也适用!!!问题中的代码是正确的。是否需要将autogenerateColumns设置为false?我是C#和VS的新手,所以我需要一些有用的易于理解的指针。逻辑或代码中没有任何错误。。。我已经更新了我有多傻。谢谢你的努力
 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;
            }