0

I'm not 100% familiar with the low-level implementation details of the dynamic keyword and the use of the ExpandoObject class so this might be a silly question, but I'm setting the DisplayMember and ValueMember of a combobox and then instantiating an ExpandoObject object and adding it to the ComboBox but the display and value members don't seem to be picked up. This is my code in a standard C# WinForms application:

    private void Form1_Load(object sender, EventArgs e)
    {
        dynamic eo = new ExpandoObject();
        eo.DisplayMember = "Hello";
        eo.ValueMember = 0;

        comboBox1.DisplayMember = "DisplayMember";
        comboBox1.ValueMember = "ValueMember";

        comboBox1.Items.Add(eo);
    }

However, the display text for the item is "System.Dynamic.ExpandoObject". I have instead created a custom class to use for this which does work but I would like to know why the ExpandoObject doesn't work. If anyone could possibly point me in the right direction here I would really appreciate it.

macmatthew
  • 302
  • 2
  • 9

1 Answers1

1

ExpandoObject cannot be used unless you create a custom TypeDescriptionProvider for it.

You have two options here though. You can either use a simpler approach and use an anonymous object instead or create a TypeDescriptionProvider for ExpandoObject.

If your code is as simple as your example, you're able to do this:

private void Form1_Load(object sender, EventArgs e)
{
    var eo = new {
        DisplayMember = "Hello",
        ValueMember = 0
    };

    comboBox1.DisplayMember = "DisplayMember";
    comboBox1.ValueMember = "ValueMember";

    comboBox1.Items.Add(eo);
}

However, if you have to use the ExpandoObject, you'll have to create a custom TypeDescriptionProvider similar to the one here.

Community
  • 1
  • 1
Marcio Rinaldi
  • 3,305
  • 24
  • 23
  • that is awesome, thank you so much! I don't know how long it would have taken me to come across that via normal research. Thanks again, much appreciated! – macmatthew Mar 16 '16 at 12:58