POJO:
class ComboBoxItem { string _text; string _value; public string Text { get { return _text; } set { _text = value; } } public string Value { get { return _value; } set { _value = value; } } public override String ToString() { return this.Value; } }
Init:
private void SurferWithProxy_Load(object sender, EventArgs e) { intiComboBox(); } private void intiComboBox() { ComboBoxItem cbi = new ComboBoxItem(); cbi = new ComboBoxItem(); cbi.Text = "test1"; cbi.Value = "Value1"; this.cboURL.Items.Add(cbi); cbi = new ComboBoxItem(); cbi.Text = "test2"; cbi.Value = "Value2"; this.cboURL.Items.Add(cbi); cbi = new ComboBoxItem(); cbi.Text = "test3"; cbi.Value = "Value3"; this.cboURL.Items.Add(cbi); cbi = new ComboBoxItem(); cbi.Text = "test4"; cbi.Value = "Value4"; this.cboURL.Items.Add(cbi); this.cboURL.DisplayMember = "Text"; this.cboURL.ValueMember = "Value"; }
Click: private void btnStart_Click(object sender, EventArgs e) { string url = ((ComboBoxItem)this.cboURL.SelectedItem).Value; MessageBox.Show(url); }
补充:
ComboBox控件添加项有两种方法:
一、编程方式添加:
使用comboBox.Items.Add(ojbect item)方法添加一个项
private void DoBindData() { for (int i = 0; i < 5; i++) { comboBox1.Items.Add(i + 1); } }
二、进行数据源绑定:
private void DoBindDataSource() { //构造数据源(或从数据库中查询) DataTable ADt = new DataTable(); DataColumn ADC1 = new DataColumn("F_ID", typeof(int)); DataColumn ADC2 = new DataColumn("F_Name", typeof(string)); ADt.Columns.Add(ADC1); ADt.Columns.Add(ADC2); for (int i = 0; i < 3; i++) { DataRow ADR = ADt.NewRow(); ADR[0] = i+1; ADR[1] = "Name_" + (i+1); ADt.Rows.Add(ADR); } //进行绑定 comboBox1.DisplayMember = "F_Name";//控件显示的列名 comboBox1.ValueMember = "F_ID";//控件值的列名 comboBox1.DataSource = ADt; }
三、其他操作和常用属性:
1)Text属性:获取当前显示的文本
2)SelectedText属性:获得当前选中的文本(控件获得光标且DropDown属性不为DropDownList)
注意:但应注意,所选内容会因用户交互而自动更改。如Button的Click事件中,SelectedIndexChanged 或 SelectedValueChanged 事件中,此属性会返回空字符串(参见MSCN:http://msdn.microsoft.com/zh-cn/partners/system.windows.forms.combobox.selectedtext(VS.90).aspx )
3)SelectedValue属性:当前显示项对应的Value值(仅在绑定数据源时,设置了ValueMember时才可以用)
4)SelectedItem属性:控件当前选中项
5)SelectedIndex属性:当前选中项的索引
http://rsljdkt.iteye.com/blog/826941