【问题标题】:Is it possible to have the datasource of a asp.net repeater be a list<string> that is a property of a class?是否可以将 asp.net 中继器的数据源作为类属性的 list<string> ?
【发布时间】:2012-05-18 04:11:11
【问题描述】:

这是我的中继器的 aspx:

<asp:Repeater ID="rpt_Files" runat="server">
    <HeaderTemplate>
       <th><asp:Label runat="server" ID="lbl_FileNameHeader" Text="File Name" /></th>                       
    </HeaderTemplate>
    <ItemTemplate>            
           <asp:Label runat="server" ID="lbl_FileName" Text='<%# Eval("JobFileNames")  %>' />
    </ItemTemplate>       
</asp:Repeater>

下面是用C#绑定数据的代码:

rpt_Files.DataSource = CurrentQuote;
    rpt_Files.DataBind();

这是 CurrentQuote 的类定义:

public class CurrentQuote
{
// Properties
private List<string> _jobfilenames;
public List<string> JobFileNames
{
    get
    {
        if (_jobfilenames != null)
            return _jobfilenames;
        else
        {
            _jobfilenames = new List<string>();
            return _jobfilenames;
        }
    }

    set { _jobfilenames = value; }
}

这是我收到的错误:

An invalid data source is being used for rpt_Files. A valid data source must implement either IListSource or IEnumerable.

如果我将转发器数据源更改为 CurrentQuote.JobFileNames,我会收到一条错误消息,指出该字符串没有名为“JobFileNames”的属性。

【问题讨论】:

    标签: asp.net repeater datasource


    【解决方案1】:

    如果您有一个包含多个文件的引用,您的 DataSource 应该如下所示:

    CurrentQuote cq = new CurrentQuote();
    string[] filenames = new string[] { "file1", "file2", "file3" };
    cq.JobFileNames = filenames.ToList();
    
    rpt_Files.DataSource = cq.JobFileNames;
    rpt_Files.DataBind();
    

    然后在标记中你可以使用:

    <asp:Label runat="server" ID="lbl_FileName" Text='<%# Container.DataItem %>' />
    

    所以是的,“可以让 asp.net 中继器的数据源成为一个作为类属性的列表”,但是您应该首先实例化该类,并且您必须从标记中直接访问 DataItem,因为它是一个字符串。

    【讨论】:

      【解决方案2】:

      您应该将 DataSource 分配给这样的对象列表:

      List<CurrentQuote> myCurrentQuoteList = new List<CurrentQuote>();
      CurrentQuote  currentQuoteObj = new CurrentQuote();  
      currentQuoteObj.JobFileNames.Add("test");
      myCurrentQuoteList.Add(myCurrentQuoteList );  
      
      rpt_Files.DataSource = myCurrentQuoteList;
      rpt_Files.DataBind();
      

      您不能直接分配类 Object,您应该实现 IListSource 或 IEnumerable 以用作您的数据源。

      【讨论】:

      • 没有 .SingleItemDataSource 很臭
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 2017-08-01
      • 2011-06-11
      • 2011-12-05
      • 2019-10-19
      相关资源
      最近更新 更多