發布時間:2020-08-06 10:07 作者:獨孤劍 閱讀:2854
新建Form窗體,拖動ComboBox控件,3個Button按鈕控件
public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// ComboBoxItem /// </summary> public class ComboBoxItem { /// <summary> /// 文本 /// </summary> public string Text { get; set; } /// <summary> /// 值 /// </summary> public int Value { get; set; } /// <summary> /// 輸出 /// </summary> /// <returns></returns> public override string ToString() { return Text; } } /// <summary> /// 使用方式1 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { comboBox1.Items.Clear(); ComboBoxItem item = new ComboBoxItem(); item.Text = "未知"; item.Value = 0; this.comboBox1.Items.Add(item); item = new ComboBoxItem(); item.Text = "男"; item.Value = 1; this.comboBox1.Items.Add(item); item = new ComboBoxItem(); item.Text = "女"; item.Value = 2; this.comboBox1.Items.Add(item); // 選中默認 comboBox1.SelectedIndex = 1; // 獲取選中項 ComboBoxItem comboBoxItem = (ComboBoxItem)comboBox1.SelectedItem; // 顯示值 MessageBox.Show("顯示值:" + comboBoxItem.Text.ToString()); // 實際值 MessageBox.Show("實際值:" + comboBoxItem.Value.ToString()); } /// <summary> /// 使用方式2 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { comboBox1.Items.Clear(); List<ComboBoxItem> items = new List<ComboBoxItem>(); ComboBoxItem item = new ComboBoxItem(); item.Text = "未知"; item.Value = 0; items.Add(item); item = new ComboBoxItem(); item.Text = "男"; item.Value = 1; items.Add(item); item = new ComboBoxItem(); item.Text = "女"; item.Value = 2; items.Add(item); // 非必要設置 comboBox1.DataSource = items; comboBox1.DisplayMember = "Text"; comboBox1.ValueMember = "Value"; // 選中默認 comboBox1.SelectedIndex = 2; // 獲取選中項 MessageBox.Show("顯示值:" + comboBox1.Text.ToString()); MessageBox.Show("實際值:" + comboBox1.SelectedValue.ToString()); } /// <summary> /// 使用方式3 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { comboBox1.Items.Clear(); DataTable dt = new DataTable(); dt.TableName = "dt"; dt.Columns.Add("Text"); dt.Columns.Add("Value"); DataRow dr = dt.NewRow(); dr["Text"] = "未知"; dr["Value"] = "0"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Text"] = "男"; dr["Value"] = "1"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["Text"] = "女"; dr["Value"] = "2"; dt.Rows.Add(dr); this.comboBox1.DataSource = dt; this.comboBox1.DisplayMember = "Text"; this.comboBox1.ValueMember = "Value"; // 選中默認 comboBox1.SelectedIndex = 1; // 獲取選中項 MessageBox.Show("顯示值:" + comboBox1.Text.ToString()); MessageBox.Show("實際值:" + comboBox1.SelectedValue.ToString()); } }
推薦采用方式一
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞