How can I use a List<> Collection as a Repeater Datasource in ASP.NET with C#

SilverLight picture SilverLight · Oct 11, 2011 · Viewed 33.3k times · Source

I have a list collection like below :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FileExplorer.Classes
{
    public class NewAddedFiles
    {
        public string FileName;
        public string FilePath;
        public DateTime FileCreationDate;
    }
}

private void GetFilesFromDirectory(string PhysicalPath)
{
    DirectoryInfo Dir = new DirectoryInfo(PhysicalPath);
    FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories);
    List<NewAddedFiles> list = new List<NewAddedFiles>();
    NewAddedFiles NewAddedFile = new NewAddedFiles();
    foreach (FileInfo FI in FileList)
    {
        //Response.Write(FI.FullName);
        //Response.Write("<br />");
        string AbsoluteFilePath = FI.FullName;
        string RelativeFilePath = "~//" + AbsoluteFilePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
        NewAddedFile.FileName = FI.Name;
        NewAddedFile.FilePath = RelativeFilePath;
        NewAddedFile.FileCreationDate = FI.CreationTime;
        list.Add(NewAddedFile);
    }
    Repeater1.DataSource = ????????????;
    Repeater1.DataBind();
}

My repeater in aspx is like below :

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("FileName") %>'></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text='<%# Eval("FilePath") %>'></asp:Label>
        <br />
        <asp:Label ID="Label3" runat="server" Text='<%# Eval("FileCreationDate") %>'></asp:Label>
    </ItemTemplate>
</asp:Repeater>

How can I set repeater datasource as that List<> Collection and use it for filling repeated labels?

EDIT :
error appeared after setting Repeater1.DataSource = list;
or
after adding some code in Item_DataBound of that repeater like that answer

DataBinding: 'FileExplorer.Classes.NewAddedFiles' does not contain a property with the name 'FileName'.

Answer

CodingGorilla picture CodingGorilla · Oct 11, 2011

Just set your list as the DataSource:

Repeater1.DataSource = list;

EDIT

You don't have actual Properties, you're using Fields. You need to create actual properties in order for the databinding to find them.

So modify your class like:

public class NewAddedFiles
{
    public string FileName { get; set; }
    public string FilePath { get; set; }
    public DateTime FileCreationDate { get; set; }
}