Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
hello sir.
I have a folder contained multiple text files. I want to read those files and bind to gridview. I written following code
C#
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();

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.
Posted
Updated 6-Mar-11 18:18pm
v2

1 solution

Try it this way,

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


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.
 
Share this answer
 
Comments
sathish.jampala 7-Mar-11 7:33am    
hello sir. thanks for ur quick reply.
this is showing the same output. no files are displaying in gridview.
gridview is displaying empty with heading only.
Prerak Patel 7-Mar-11 23:32pm    
Try to debug your code and add some more details then.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900