如何使用Repeater从对象列表输出字符串

时间:2011-08-02 04:18:46

标签: c# .net list data-binding repeater

我不确定这是否是解决此问题的最佳方式,但我正在尝试使用转发器控件显示一些搜索结果。查询写在页面后面的代码中,我无法弄清楚如何将结果绑定到控件。到目前为止,我已经创建了一个saleItem对象列表,saleItem对象包含我想在转发器中显示的字符串。

Search.aspx.cs

List<SaleItem> resultsList = new List<SaleItem>();

  SqlDataReader reader = doMainQuery.ExecuteReader();

  while (reader.Read())
  {
    SaleItem newItem = new SaleItem((string)reader["saleTitle"]);
    resultsList.Add(newItem);
  }
  showResults.DataSource = resultsList;
  showResults.DataBind();

SaleItem.cs

public class SaleItem
{
    private String connectionString;
    public string saleTitle;

    public SaleItem(string s)
    {
        saleTitle = s;
    }

    public string  getTitle()
    {
        return saleTitle;
    }
}

Search.aspx

id喜欢能够以类似的方式显示标题,任何想法?

<asp:repeater
        id="showResults"  

        Runat="server"   >

        <ItemTemplate>
        <%# Eval("saleTitle")%></ItemTemplate> // resultsList.SaleItem.getTitle()?
        </asp:repeater>

1 个答案:

答案 0 :(得分:1)

您可以按照以下方式重构代码

public class SaleItem
{    
    public string saleTitle {get;set;}   
}

public static class Extension
{
    public static IEnumerable<T> Select<T>(this SqlDataReader reader, Func<SqlDataReader, T> projection)
    {
        while (reader.Read())
        {
            yield return projection(reader);
        }
    }
}

List<SaleItem> resultsList = new List<SaleItem>();

SqlDataReader reader = doMainQuery.ExecuteReader();
var resultsList = reader.Select(x => new SaleItem { saleTitle = x["saleTitle"].ToString() }).Distinct().ToList();

showResults.DataSource = resultsList;
showResults.DataBind();


<asp:repeater id="showResults" Runat="server"   >
    <ItemTemplate>
      <%# Eval("saleTitle")%>
    </ItemTemplate>
</asp:repeater>