开发者

Does databinding to dynamics and ExpandoObjects work in .NET

开发者 https://www.devze.com 2023-04-06 00:57 出处:网络
For the life of me I I don\'t seem to be able to get Databinding to Dynamics or ExpandoObjects working.

For the life of me I I don't seem to be able to get Databinding to Dynamics or ExpandoObjects working.

I have tried this in WinForms and in WebForms and get different results in each:

In 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();

    }

This results in:

DataBinding: 'System.Dynamic.ExpandoObject' does not contain a property with the name 'Name'.

In WinForms, I have a different issue:

        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";

This results in the ComboBox displaying "System.Dynamic.ExpandoObject" - as it is just calling ToString() on the two items开发者_运维百科 in the collection. :(

I appreciate the help!


Try this

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

精彩评论

暂无评论...
验证码 换一张
取 消