5

在我的一生中,我似乎无法让数据绑定到 Dynamics 或 ExpandoObjects 工作。

我已经在 WinForms 和 WebForms 中尝试过这个并在每个中得到不同的结果:

在 ASP.NET 中:

<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>

    protected void Page_Load(object sender, EventArgs e)
    {
        dynamic contacts = new List<dynamic>();

        contacts.Add(new ExpandoObject());
        contacts[0].Name = "Patrick Hines";
        contacts[0].Phone = "206-555-0144";

        contacts.Add(new ExpandoObject());
        contacts[1].Name = "Ellen Adams";
        contacts[1].Phone = "206-555-0155";


        DropDownList1.DataSource = contacts;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataBind();

    }

这导致:

DataBinding:“System.Dynamic.ExpandoObject”不包含名为“Name”的属性。

在 WinForms 中,我有一个不同的问题:

        dynamic contacts = new List<dynamic>();

        contacts.Add(new ExpandoObject());
        contacts[0].Name = "Patrick Hines";
        contacts[0].Phone = "206-555-0144";

        contacts.Add(new ExpandoObject());
        contacts[1].Name = "Ellen Adams";
        contacts[1].Phone = "206-555-0155";

        this.departmentList.DataSource = contacts;
        this.departmentList.DisplayMember = "Name";

这导致 ComboBox 显示“System.Dynamic.ExpandoObject” - 因为它只是在集合中的两个项目上调用 ToString()。:(

感谢您的帮助!

4

1 回答 1

0

尝试这个

var contacts = new List<dynamic>()
{
    new {Name = "Patrick Hines",Phone = "206-555-0144"},
    new {Name = "Ellen Adams",Phone = "206-555-0155"}
};
于 2016-03-19T20:13:35.273 回答