【问题标题】:Exporting data from text file to gridview将数据从文本文件导出到gridview
【发布时间】:2016-03-05 09:43:50
【问题描述】:

我正在尝试将数据从文本文件导出到 c# 中的 gridview。仅包含数字的文本文件。 文本文件格式 1313232、12323232、7676768、8786868、……

我需要将表格列设置为 10,然后设置新行,直到文本文件中的数字完成。 谢谢。

【问题讨论】:

  • 使用阅读器将文件作为单个字符串导入,.Split(',') 字符串,解析结果数组并创建一种将其放入 DataTable 的方法。使用 DataTable 作为 GridView 的源并绑定它。你有尝试过的例子吗?

标签: c# visual-studio gridview export


【解决方案1】:

我希望这不是你的作业。如果是这样,请以改进这个有点笨拙的代码为己任。您还必须使用 System.IO 读取文件并将其放入字符串中。

ASP.NET

<asp:GridView ID="gvNumbers" runat="server" AutoGenerateColumns="true"></asp:GridView>

C#

var dt = new DataTable();
string fileText = "1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,1313232 , 10, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 20,1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,1313232 , 12323232, 7676768, 8786868,";
string[] nums = fileText.Split(',');
//set up columns
for (int i = 1; i < 11; i++)
{
    dt.Columns.Add("Col" + i, typeof(int)); //add integer columns and name them
}
int colCount = 0;
int[] oneRow = new int[10];
int n, failCount = 0;
foreach (string s in nums)
{
    if (int.TryParse(s, out n))
    {
        oneRow[colCount] = n;
        colCount++;
    }
    else  //invalid integer
    {
        failCount++;  //you could use this value if you want to see if the file was fully valid or not.
    }
    //check if row is complete
    if (colCount == 10)
    {
        dt.Rows.Add(oneRow[0], oneRow[1], oneRow[2], oneRow[3], oneRow[4], oneRow[5], oneRow[6], oneRow[7], oneRow[8], oneRow[9]);
        colCount = 0;
        oneRow = new int[10]; //reset array
    }
}
if (colCount > 0) dt.Rows.Add(oneRow[0], oneRow[1], oneRow[2], oneRow[3], oneRow[4], oneRow[5], oneRow[6], oneRow[7], oneRow[8], oneRow[9]); //add final incomplete row

//reference the DataTable as a source to the GridView and bind it.
gvNumbers.DataSource = dt;
gvNumbers.DataBind();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2020-09-05
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多