使用Linq的数据绑定两个属性

时间:2016-06-11 12:12:41

标签: asp.net

我认为我的linq查询没有产生任何结果,因为“Stock”对象没有被实例化。欢迎任何帮助!

在我班上:

   public class Stock
{
    public List<string> Names { get { return NamesList(); } }
    public List<int> Prices { get { return PriceList(); } }

        private List<int> PriceList()
    {

        Random random = new Random();
        List<int> stockPriceList = new List<int>();
        stockPriceList.Add(random.Next(100, 220));
        stockPriceList.Add(random.Next(1000, 5365));
        return stockPriceList;
    }

    private List<string> NamesList()
    {
        List<string> stockNames = new List<string>();
        stockNames.Add("CBA");
        stockNames.Add("ANZ");
         return stockNames;
    }

}

在我的数据绑定方法中。 Lync查询不会产生任何结果。

private void bindPriceList()
    {

        List<Stock> stockList = new List<Stock>();

        rptPriceList.DataSource = stockList.Select(s => new { Name = s.Names, Price = s.Prices });

        rptPriceList.DataBind();
    }

1 个答案:

答案 0 :(得分:1)

请改为尝试:

代码背后:

public partial class RepeaterExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            this.bindPriceList();
        }
    }

    private void bindPriceList()
    {
        var stock1 = new Stock { Name = "CBA", Price = "12.99" };
        var stock2 = new Stock { Name = "ANZ", Price = "13.99" };
        rptPriceList.DataSource = new List<Stock> { stock1, stock2 };
        rptPriceList.DataBind();
    }
}

public class Stock
{
    public string Name { get; set; }
    public string Price { get; set; }
}

<强> .ASPX:

<asp:Repeater ID="rptPriceList" runat="server">
    <ItemTemplate>
        <p><%# Eval("Name") %> - <%# Eval("Price") %></p>
    </ItemTemplate>
</asp:Repeater>