How to output strings from a list of Objects using Repeater
I'm not sure if this is the best way to go about this but I'm trying to show some search results using a repeater control. The query is written in the code behind page and i cant figure out how to bind the results to the control. So far I've created a list of saleItem objects, the saleItem object contains the string i want to show in the repeater.
Search.aspx.cs
List<SaleItem> resultsList = new List<SaleItem>();
SqlDataReader reade开发者_高级运维r = 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 like to be able to show the title in a similar way to this, any ideas?
<asp:repeater
id="showResults"
Runat="server" >
<ItemTemplate>
<%# Eval("saleTitle")%></ItemTemplate> // resultsList.SaleItem.getTitle()?
</asp:repeater>
You can refactor your code as follow
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>
精彩评论