2017-04-16 50 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();