ListBox, list of the different objects implementing the same interface

advertisements

I have two objects: User and Client, both implements interface IMember

interface IMember
{
     int Id { get; set; }
     string Name { get; set; }
}

In a form I set ListBox data source:

myListBox.DisplayMember = "Name";
myListBox.ValueMember = "Id";
myListBox.DataSource = membersList; // List<IMember>

And wierd things happen ;) When I run program the first object, whichis type of User, displays correctly (Adrian Serafin) and other objects, wich are type of Contact are displayed like this:

MyProject.Client#20
MyProject.Client#40

as for display was ToString() call on them.

I can't using list of different objects implementing the same interface as datasource in ListBox or I made some mistake here?


Are you sure it is List<IMember>, and not ArrayList? This makes a big difference, as the existence of a non-object public indexer (public SomeType this[int] {get;set;}) makes a big difference. The following works fine:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
interface IMember
{
    int Id { get; set; }
    string Name { get; set; }
}
class Foo : IMember
{
    public int Id { get; set; }
    public string Name { get; set; }
}
class Bar : IMember
{ // explicit, why not...
    int IMember.Id { get; set; }
    string IMember.Name { get; set; }
}
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        IMember bar = new Bar();
        bar.Id = 2;
        bar.Name = "def";
        var list = new List<IMember> {
            new Foo { Id = 1, Name = "abc"},
            bar,
        };
        Application.Run(new Form
        {
            Controls = {
                new ListBox {
                    Dock = DockStyle.Fill,
                    DisplayMember = "Name",
                    ValueMember = "Id",
                    DataSource = list
                }
            }
        });

    }
}