C# WinForm ComboBox Items 选定值

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

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

class User
{
public int id { get; set; }
public string name { get; set; }
}


private void Form1_Load(object sender, EventArgs e)
{
List
<User> collection = new List<User>
{
new User { id = 1, name = "Lin" },
new User { id = 2, name = "Tom" },
new User { id = 3, name = "Jack" },
};

this.comboBox1.DisplayMember = "name";
this.comboBox1.ValueMember = "id";
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

//Items 加载 默认选择为空
//DataSoursce 加载 默认选择为首项
this.comboBox1.Items.Clear();
this.comboBox1.Items.AddRange(collection.ToArray());
//this.comboBox1.DataSource = collection;
}

//设置选择 id = 2 的 User
private void button1_Click(object sender, EventArgs e)
{
var items
= this.comboBox1.Items;
for (int i = 0; i < items.Count; i++)
{
User item
= items[i] as User;
if (item.id == 2)
{
this.comboBox1.SelectedItem = item;
break;
}
}
}
}
}

  

posted @ 2011-07-21 11:37  一浩瀚星空一  阅读(8065)  评论(0编辑  收藏  举报