如何从文本文件导入到asp.net GridView

时间:2017-04-16 14:20:28

标签: c# asp.net .net gridview datatable

我尝试使用自动代码将数据从文本文件导入网格视图:

DataTable dt = new DataTable();
using (System.IO.TextReader tr = File.OpenText((@"d:\\My File3.log")))
{
    string line;
    while ((line = tr.ReadLine()) != null)
    {

        string[] items = line.Trim().Split(' ');
        if (dt.Columns.Count == 0)
        {
            // Create the data columns for the data table based on the number of items
            // on the first line of the file
            for (int i = 0; i < items.Length; i++)
                dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
        }
        dt.Rows.Add(items);

    }
    //show it in gridview 
    this.GridView1.DataSource = dt;
    this.GridView1.DataBind();

我的文件就像:

A B C

E F D C C

E D D D

D P

然后我收到以下错误

  

输入数组比c#application

中此表中的列数长

1 个答案:

答案 0 :(得分:0)

尝试从列计数开始循环到项目数组长度。

DataTable dt = new DataTable();
using (System.IO.TextReader tr = File.OpenText((@"d:\\My File3.log")))
{
string line;
while ((line = tr.ReadLine()) != null)
{

    string[] items = line.Trim().Split(' ');
    if (dt.Columns.Count < items.Length)
    {
        // Create the data columns for the data table based on the number of items
        // on the first line of the file
        for (int i = dt.Columns.Count; i < items.Length; i++)
            dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
    }
    dt.Rows.Add(items);

}
//show it in gridview 
this.GridView1.DataSource = dt;
this.GridView1.DataBind();