user1701856
user1701856

Reputation: 71

Databinding from text file to gridview

I'm attempting to read a text file, place it into an array separating each entry by \t or \n, then displaying it to a gridview. Here is my code:

    private void importExcel()
    {
        //read in textfile and place it into a datatable
        StreamReader reader = new StreamReader("testfile.txt");
        string[] words = reader.ReadToEnd().Split('\t','\n');

        ReleasePortal.DataSource = words;
        ReleasePortal.DataBind();
    }

    <asp:GridView ID="ReleasePortal" runat="server">
    </asp:GridView>`      

What ends up happening is all the data is placed into a single column even if I create extra columns in gridview. I understand how to get it to work if I were to use a database using DataTextField and DataValueField. Since I am retrieving this data from a textfile(converted from excel) it has no field identifiers and I dont understand how to put the data into the correct format in gridview. I can do this directly from the excel file but I need to do this from a text file though. Any ideas?

Upvotes: 0

Views: 235

Answers (1)

Tomas Pastircak
Tomas Pastircak

Reputation: 2857

the words are one-dimensional array, you want to create a table. You should define a type representing the line (use correct descriptive names, of course):

public class Foo
{
    public string Col0 { get; set; }

    public string Col1 { get; set; }

    public string Col2 { get; set; }
}

Then, you should first split the result per lines and then by columns, like this:

string[] lines = reader.ReadToEnd().Split('\n');
    List<Foo> data = new List<Foo>();
    foreach (var line in lines)
    {
        string[] words = line.Split('\n');
        var gridLine = new Foo { Col0 = words[0], Col1 = words[1], Col2 = words[2] };
        data.Add(gridLine);
    }
    ReleasePortal.DataSource = data;
    ReleasePortal.DataBind();

Upvotes: 1

Related Questions