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