如何将多个文本文件从文件夹绑定到asp.net中的gridview [英] how to bind multiple textfiles from folder to gridview in asp.net

查看:66
本文介绍了如何将多个文本文件从文件夹绑定到asp.net中的gridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好先生.
我有一个包含多个文本文件的文件夹.我想阅读这些文件并绑定到gridview.我写了以下代码

hello sir.
I have a folder contained multiple text files. I want to read those files and bind to gridview. I written following code

string[] files = Directory.GetFiles("E:\\DOTNET APPLICATIONS\\Asp.net\\TextfilestoGrid\\TextFolder\\");

            foreach (string file in files)
            {
                Stream msgStream = File.Open(file, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(msgStream);
                string str = sr.ReadToEnd();
                //ArrayList al = new ArrayList();
                
                DataTable dt = new DataTable();
                dt.Columns.Add("TextFiles");
                DataRow dr = dt.NewRow();
                dr["TextFiles"] = str;
                dt.Rows.Add(dr);
                sr.Close();
                msgStream.Close();
                GV.DataSource = dt;
                GV.DataBind();


每当我调试应用程序时,所有文件都将流对象,但它们未绑定到gridview.输出仅显示一个列名,即"TextFiles",没有数据.
请帮助我;
谢谢.


when ever I debug the application, all files are coming to stream object but they are not binded to gridview. output is displaying only one column name that is "TextFiles" with no data.
please help me;
thanking you.

推荐答案

尝试这种方式,

Try it this way,

DataTable dt = new DataTable();
dt.Columns.Add("TextFiles"); 

            string[] files = Directory.GetFiles("E:\\DOTNET APPLICATIONS\\Asp.net\\TextfilestoGrid\\TextFolder\\");
            foreach (string file in files)
            {
string str = IO.File.ReadAllText(file);
                
                DataRow dr = dt.NewRow();
                dr["TextFiles"] = str;
                dt.Rows.Add(dr);
            }

GV.DataSource = dt;
GV.DataBind();



您将在每次迭代中创建新的数据表,并将您的网格绑定到该表,这是不正确的方法.此外,IO.File.ReadAllText是从文件读取文本内容的好方法.



You are creating new datatable in each iteration and binding your grid to it, which is not correct approach. Moreover, IO.File.ReadAllText is a good approach to read the text content from file.


这篇关于如何将多个文本文件从文件夹绑定到asp.net中的gridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆