Denis Brat
Denis Brat

Reputation: 497

Use a object property as the DisplayMember in ListBox

I want to use a property of an object that's inside an object. Is there a way to achieve this?

WebProxy proxy = new WebProxy("127.0.0.1:80");
ListBox listBox = new ListBox();
listBox.DisplayMember = **"Address.Authority"**; //Note: Address.Authority is an property inside the WebProxy object
listBox.Items.Add(proxy);

Thanks.

Upvotes: 1

Views: 3085

Answers (2)

Kamran Khan
Kamran Khan

Reputation: 9986

How about you subclass WebProxy to, for instance, WebProxyEx and implement the IList interface which sort of(expects an object that implements the IList or IListSource interfaces) is a pre-requisite to use the .DataSource property of listbox. Like following:

class WebProxyEx : WebProxy, IList
    {
        private object[] _contents = new object[8];
        private int _count;

        public WebProxy w;

        public WebProxyEx(string address)
        {
            _count = 0;
            w = new WebProxy(address);
            this.Add(w.Address.Authority);
        }
...

And use it like:

ListBox lb;
public Form1()
{
    InitializeComponent();
    WebProxyEx w = new WebProxyEx("127.0.0.1:80");//Use your sub class
    lb = new ListBox();
    this.Controls.Add(lb);

    lb.DataSource = w;//assign the datasource.
    //lb.DisplayMember = "Address.Authority"; //Automatically gets added in the WebProxEx constructor.

}

Gives following output in the listbox:

127.0.0.1

Upvotes: 0

Bradley Smith
Bradley Smith

Reputation: 13601

Have a look at this question, it is essentially asking the same thing - the principle does not change between DataGridView and ListBox. Short answer: it's possible, but convoluted.

Upvotes: 1

Related Questions