【问题标题】:How to import from text file to asp.net GridView如何从文本文件导入到 asp.net GridView
【发布时间】:2017-04-16 14:20:28
【问题描述】:

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

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

DP

然后我得到以下错误

输入数组长于c#应用中此表的列数

【问题讨论】:

  • 您正在创建 3 列,因为那是文件的第一行。文件的下一行尝试添加 5。
  • 如何解决?
  • 如果您是该代码的作者,那么我相信您可以弄清楚。这应该是微不足道的,我会通过解决它来伤害你。这是你的代码还是你在维护别人的代码?

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多