在C#中将CSV文件导出到DataGridview

问题描述 投票:-1回答:2

我正在使用以下代码将CSV文件内容导出到C#中的DataGridView。我的Windows应用程序已成功运行,但甚至不显示Datagridview或输出中的任何内容。

我不知道确切的问题在哪里。

我的目标是在datagridview中显示.csv文件的内容。我已将.csv文件存储在我的C驱动器中,如路径中所指定。

Using System.data.Odbc;

namespace finaltry
{
    public partial class Form1 : Form
    {

        private void Form1_Load(object sender, System.EventArgs e)
        {


            string  ConnectionString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=c:\;Extensions=asc,csv,tab,txt";

            OdbcConnection conn = new OdbcConnection(ConnectionString);
            try
            {
                conn.Open();
                OdbcDataAdapter da = new OdbcDataAdapter("Select * FROM SharedIncidents.csv", conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "SharedIncidents");
                dataGridView1.DataSource = ds.DefaultViewManager;
                conn.Close(); 

            }
            catch (System.Exception)
            {

                MessageBox.Show("error is" );



            }

        }
    }
}

我的应用程序运行成功,但没有在datagridview中显示任何内容。谁能告诉我问题出在哪里?

c# .net
2个回答
0
投票

请尝试使用此示例代码,这很好,我可以将csv内容绑定到Gridview控件。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CSVSample.aspx.cs" Inherits="CSVSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView runat="server" ID="gv_csvupload">
    </asp:GridView>
    </div>
    </form>
</body>
</html>

代码隐藏

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
public partial class CSVSample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "E:\\FolderName\\" + ";Extended Properties='text;HDR=Yes'";
        //sample.csv is the csv which i used for my demo
        string CommandText = "select * from Sample.csv";
        OleDbConnection conn = new OleDbConnection(ConnectionString);
        conn.Open();
        OleDbDataAdapter da=new OleDbDataAdapter(CommandText,conn);
        DataSet Sample=new DataSet();
        da.Fill(Sample);
        conn.Close();
        conn.Dispose();
        gv_csvupload.DataSource = Sample;
        gv_csvupload.DataBind();                
    }
}

0
投票

正如@Ramakrishnan在他的样本中提到的......我认为你唯一缺少的就是

dataGridView1.DataBind();

子句......基本上将数据推入网格中进行显示。

© www.soinside.com 2019 - 2024. All rights reserved.