一个listBox1,如果它的项并非是同一个类的对象,比如有Perosn类和Student两个类,要求Person的对象显示Name属性值,Student对象显示aaaa属性值。
如何设置项的实际显示的内容?

解决方案 »

  1.   

    Person 类重载
    public overwrite  void ToString()
    {
       return this.Name;
    }Student 类重载 public overwrite void ToString()
    {
      return this.aaaa;
    }
      

  2.   

    这个应该借助于一个列表List<string>,把Perosn Name属性和其他属性的值放如列表中,然后绑定列表
      

  3.   

    我是问,如何设置DisplayMember属性
      

  4.   

    那没法实现,只能以Items.Add的方式加入才行,就按我上面说的。即可。
      

  5.   

    研究了下 可以达到lz想要的效果public partial class Form7 : Form
        {
            public Form7()
            {
                InitializeComponent();
            }        /// <summary>
            /// Person基类
            /// </summary>
            public class Person
            {
                public string ID { get; set; }
                public string PName { get; set; }
                /// <summary>
                /// 此属性用于设置为显示字段
                /// </summary>
                public virtual string Show
                {
                    get
                    {
                        return this.PName;
                    }
                    set
                    {
                        this.PName = value;
                    }
                }
            }        /// <summary>
            /// 学生子类
            /// </summary>
            public class Student : Person
            {
                public string aa { get; set; }
                /// <summary>
                /// 重写父类的show属性
                /// </summary>
                public override string Show
                {
                    get
                    {
                        return this.aa;
                    }
                    set
                    {
                        this.aa = value;
                    }
                }
            }        private void Form7_Load(object sender, EventArgs e)
            {
                //实例化Person类
                Person p = new Person() { ID="1",PName="John"};
                //实例化Student类 这里需要注意要用父类new子类 否则下面的泛型集合无法接受不同类型
                Person s = new Student() { ID="2" , PName="Paul" ,aa="aa"};
                List<Person> li = new List<Person>();
                li.Add(p);
                li.Add(s);
                this.listBox1.DataSource = li;
                this.listBox1.DisplayMember = "Show";
            }
        }