Use a object property as the DisplayMember in ListBox

走远了吗. 提交于 2019-12-11 05:16:30

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4273917/use-a-object-property-as-the-displaymember-in-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!