views:

301

answers:

2

I want to read the values of each rows in a textfile to a ListBox control. The file needs to be uploaded on the client side.

I have the code to read from a fixed file but I don't know how to upload a file and then read from it.

The code to read from a normal file is:

protected void Button1_Click(object sender, EventArgs e)
{
    FileInfo file = new FileInfo("file");
    StreamReader stRead = file.OpenText();
    while (!stRead.EndOfStream)
    {
        ListBox1.Items.Add(stRead.ReadLine());
    }
}
A: 

To get a file from the client side, you have to use a file upload control.

http://www.c-sharpcorner.com/UploadFile/mahesh/FileUpload10092005172118PM/FileUpload.aspx?ArticleID=79850d6d-0e91-4d7b-9e27-a64a09b0ee6b

The file upload has a stream of the file which you can read from. However the user will have to point to the file.

David Basarab
thanks...Appreciate the quick response.
is there a way i can edit data in the listbox??
+1  A: 

I would do it like this if I were you. Hope this helps!

    protected void btnUpload_Click(object sender, EventArgs e)
{
    using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
    {
        while (!stRead.EndOfStream)
        {
            ListBox1.Items.Add(stRead.ReadLine());
        }
    }
}

BTW you'll need this in the aspx page:

    <asp:FileUpload runat="server" ID="FileUpload1"/>
    <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click" Text="Upload" />        
    <asp:ListBox runat="server" ID="ListBox1"></asp:ListBox>
Mike
thanks...This is perfect
it works good..thanks a lot
is there a way i can edit data in the listbox??
Not quite sure what you mean but you can do something like ListBox1.Items[0].Text = "Whatever";
Mike
i mean can a user edit the values in the listbox (from the file)...like change the name..
You can't edit it straight from the listbox you would have to load the selected listitem's text into a textbox first edit and then set the text property of the listitem to textbox.text. This would only update the list though not the file.
Mike
One more thing...The code works fine with .txt files bit not with the .doc and excel files. Can you help me with that