2017-04-16 21 views
-1

我试图使用自爆代码从文本文件导入数据到网格视图:如何从文本文件导入到ASP.NET GridView的

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(); 

我的文件是这样的:

ABC

EFDCC

EDDD

DP

然后我收到以下错误

输入数组比列数较长此表在C#应用程序

+0

您正在创建3列,因为这是您的文件的第一行。该文件的下一行尝试添加5. – Crowcoder

+0

如何解决它? – marwen1

+0

如果你是该代码的作者,那么我有信心,你可以弄明白。它应该是微不足道的,我会通过解决它来解决你的问题。是你的代码还是你维护别人的? – Crowcoder

回答

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();