数据绑定到动态和ExpandoObjects是否在.NET中工作

时间:2011-09-17 07:01:07

标签: data-binding expandoobject

对于我的生活,我似乎无法使数据绑定到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()。 :(

我很感激帮助!

1 个答案:

答案 0 :(得分:0)

试试这个

var contacts = new List<dynamic>()
{
    new {Name = "Patrick Hines",Phone = "206-555-0144"},
    new {Name = "Ellen Adams",Phone = "206-555-0155"}
};