listbox中添加对象(c#)

来自链接 https://bbs.csdn.net/topics/390317481

环境vs2010.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace add_object_for_listbox
{
    public partial class Form1 : Form
    {
        private List<Person> f_persons = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++)
            {
                Person person = new Person();
                person.id = i;
                person.name = String.Format("{0}{1}", "name", i);
                person.desc = String.Format("{0}{1}", "desc", i);
                f_persons.Add(person);
            }
            listBox1.DataSource = f_persons;
            listBox1.DisplayMember = "desc";
            listBox1.SelectedIndex = 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            f_persons = new List<Person>();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Person person = (Person)listBox1.SelectedItem;
            if (person == null)
            {
                return;
            }
            textBox1.Text = person.id.ToString();
            textBox2.Text = person.name;
            textBox3.Text = person.desc;
        }
    }

    public class Person
    {
        private int f_id;
        private string f_name;
        private string f_desc;

        public Person()
        { 
            
        }

        public Person(int p_id, string p_name, string p_desc)
        {
            f_id = p_id;
            f_name = p_name;
            f_desc = p_desc;
        }

        /// <summary>
        /// 此属性用于设置为显示字段
        /// </summary>
        public int id
        {
            get
            {
                return this.f_id;
            }
            set
            {
                this.f_id = value;
            }
        }

        public string name
        {
            get
            {
                return this.f_name;
            }
            set
            {
                this.f_name = value;
            }
        }

        public string desc
        {
            get
            {
                return this.f_desc;
            }
            set
            {
                this.f_desc = value;
            }
        }
    }
    

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值