views:

588

answers:

4

I'm trying to set the DisplayMember Property of my ListBox in a windows forms project to a property of a nested class inside a Generic List I am binding to.

Here's a simple example:

 public class Security
{
    public int SecurityId { get; set;}
    public SecurityInfo Info { get; set;}
}
public class SecurityInfo
{        
    public string Description { get; set;}
}
//........//
public void DoIt()
{
    List<Security> securities = new List<Security>();
    //add securities to list
    lstSecurities.DataSource = securities;
    lstSecurities.DisplayMember = "Info.Description";
}

Is this possible with a simple ListBox or will I have to create a subclassed ListBox to handle this?

edit:

I am trying not to modify these classes as they are being generated via a WSDL Document.

A: 

Just override SecurityInfo ToString method to return Description and do:

lstSecurities.DisplayMember = "Info";

If you can't modify the classes, the best option would be to use a ViewModel. A class that takes a Security and exposes the properties you want to view.

gcores
+2  A: 

You could add a new property that maps to Info.Description.

Something like this:

public string InfoDescription
{
  get { return Info.Description; }
  set { Info.Description = value; }
}

This will work. But I thought your example should work as well

Rune Grimstad
+3  A: 

No, most winforms bindings do not support child properties like this.

You can do it directly with custom type-descriptors, but that is a lot of work and not worth it.

Check the generated code; it should (with any recent version of the tools) be a partial class; that means you can add extra members in a second class file, so you don't break the wsdl-generated code - i.e.

namespace MyWsdlNamespace {
    partial class MyClass {
        public string InfoDescription {
            get { return Info.Description; }
            // and a set if you want
        }
    }
}

You should now be able to bind to "InfoDescription" fairly easily.

Marc Gravell
A: 

Worth to see is

http://www.mail-archive.com/[email protected]/msg06383.html

Maciej