Web控件DropDownList和WinForm控件ComboBox机制不一样。
ComboBox没有对应的ListItem需要自己写一个:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WinListItem { /// <summary> /// 选择项类,用于ComboBox或者ListBox添加项 /// </summary> public class ListItem { private string id = string.Empty; private string name = string.Empty; public ListItem(string sid, string sname) { id = sid; name = sname; } public override string ToString() { return this.name; } public string ID { get { return this.id; } set { this.id = value; } } public string Name { get { return this.name; } set { this.name = value; } } } }
然后可以类似DropDownList添加项:
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 WinListItem { public partial class MainFrm : Form { public MainFrm() { InitializeComponent(); } private void btnOk_Click(object sender, EventArgs e) { ListItem listItem = comboBox1.SelectedItem as ListItem; MessageBox.Show(listItem.ID + "," + listItem.Name); } private void MainFrm_Load(object sender, EventArgs e) { //添加项,Web控件DropDownList有对应的ListItem ListItem listItem0 = new ListItem("0", "选项零"); ListItem listItem1 = new ListItem("1", "选项一"); ListItem listItem2 = new ListItem("2", "选项二"); comboBox1.Items.Add(listItem0); comboBox1.Items.Add(listItem1); comboBox1.Items.Add(listItem2); //设置默认选择项,DropDownList会默认选择第一项。 comboBox1.SelectedIndex = 0;//设置第一项为默认选择项。 comboBox1.SelectedItem = listItem1;//设置指定的项为默认选择项 } } }