Question

I tried to get all the file .txt in the path and list it in the webpage as the code below :

DataTable dt = new DataTable();
dt.Columns.Add("tenalbum", typeof(String));
string dir = Server.MapPath("~") + "images\\avatar\\" + Session["Username"].ToString();
string[] files = Directory.GetFiles(dir);
foreach (string file in files)
{
   if (Path.GetExtension(file).Equals(".txt"))
       {
         DataRow dtr = dt.NewRow();
         dtr["tenalbum"] = Path.GetFileName(file);
       }
}
DataList1.DataSource = dt;
DataList1.DataBind();

in the .aspx page :

<div>
    <asp:DataList ID="DataList1" runat="server" CellPadding="4" Width="586px" CellSpacing="2"
        GridLines="Both">
        <ItemTemplate>
            <table style="border: thin solid #333333; width: 566px; margin-bottom: 3px">
                <tr>
                    <td style="width: 70px">
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("tenalbum") %>'></asp:Label>
                    </td>
                    <td class="style3">
                        <asp:ImageButton ID="imgbtn_Favorite" runat="server" ImageUrl="~/images/playAlbum.png"
                            Width="25px" CommandArgument='<%# Eval("tenalbum") %>' />
                    </td>
                </tr>
            </table>
        </ItemTemplate>
        <SelectedItemStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
    </asp:DataList>
</div>

The problem is the datasource of datalist wasn't binded anything to it. Any help would be great.

Was it helpful?

Solution

You internal loop misses a line needed to add the row to the table

if (Path.GetExtension(file).Equals(".txt"))
{
    DataRow dtr = dt.NewRow();
    dtr["tenalbum"] = Path.GetFileName(file);
    dt.Rows.Add(dtr);  // This line adds the new row to the rows collection of the table
}

By the way, you could extract only the files with txt extension using the GetFiles overload that takes a pattern argument

 string[] files = Directory.GetFiles(dir, "*.txt");

And, as final optimization, I think you could simply write

 List<string> files = Directory.GetFiles(@"d:\temp", "*.txt")
                      .Select(x => Path.GetFileName(x)).ToList();
 DataList1.DataSource = files;
 DataList1.DataBind();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top