WinForm要建立comboBox,選單的text與value是不同值,例如text為1分鐘、value為60。並將某value設為預選項。
comboBox變換選取時,顯示選擇的text、value及index。

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 TEST
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//設定ComboBox的Text及Value值
//comboBox1.Items.Add(new ComboboxItem("0z", "zero"));
//清空ComboBox
//comboBox1.Items.Clear();
//設定ComboBox的Text及Value值
comboBox1.Items.Add(new ComboboxItem("1a", "one"));
comboBox1.Items.Add(new ComboboxItem("2b", "onetwo"));
comboBox1.Items.Add(new ComboboxItem("3c", "onetwothree"));
//預設選擇項
//預設選擇value=2b之項目
var selectedObject = comboBox1.Items.Cast<ComboboxItem>().SingleOrDefault(i => i.Value.Equals("2b"));
comboBox1.SelectedIndex = comboBox1.FindStringExact(selectedObject.Text.ToString());
label1.Text = "選擇Text=" + selectedObject.Text.ToString();
label2.Text = "選擇Value=" + selectedObject.Value.ToString();
label3.Text = "選擇index=" + comboBox1.FindStringExact(selectedObject.Text.ToString()).ToString();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboboxItem item = comboBox1.Items[comboBox1.SelectedIndex] as ComboboxItem;
label1.Text = "選擇Text=" + comboBox1.Text;
label2.Text = "選擇Value=" + item.Value.ToString();
label3.Text = "選擇index=" + comboBox1.SelectedIndex.ToString();
}
private class ComboboxItem {
public ComboboxItem(string value, string text)
{
Value = value;
Text = text;
}
public string Value {
get;
set;
}
public string Text {
get;
set;
}
public override string ToString() {
return Text;
}
}
}
}