来自链接 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;
}
}
}
}