c#windows应用程序中的组合框 [英] Combo box in c# windows application

查看:77
本文介绍了c#windows应用程序中的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我如何填充组合框中的项目并在标签中显示所选项目值!!!!

例如:

显示文字(第1年,第2年)

价值(2015,2016)



当我从组合框中选择year1时,标签将显示2015

等等

请帮帮我

非常感谢

Hi all
How can i fill items in my combobox and display selected item values in label !!!!
For ex:
Display text ( year1,year2)
Values ( 2015,2016)

When i choose year1 from combobox the label will display 2015
And so on
Please help me
Thanks alot

推荐答案

方便这样做的方法是将 ComboBox绑定到作为DataSource的通用Dictionary:
A convenient way to do this is to bind the ComboBox to a generic Dictionary as a DataSource:
//required

using System;
using System.Collections.Generic;
using System.Windows.Forms;

private void Form1_Load(object sender, EventArgs e)
{
    Dictionary<string, string> ComboEntries = new Dictionary<string, string>
    {
       {"year1, year2", "2015, 2016"},
       {"year3, year4", "2017, 2018"}
    };

    comboBox1.DataSource = new BindingSource(ComboEntries, null);
    comboBox1.DisplayMember = "Key";
    comboBox1.ValueMember = "Value";
}

private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
    label1.Text = string.Format("Value selected: {0}", comboBox1.SelectedValue);
}


请按照以下步骤实现相同的目标:



Step1 :为ComboBox Listitem创建自定义类

Please follow below steps achieve the same:

Step1: Create a custom class for ComboBox Listitem
public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }
}



Step2 :创建自定义类的对象( ComboboxItem )并将这些对象添加到ComboBox


Step2: Create object of custom class(ComboboxItem) and add those objects to ComboBox

ComboboxItem item = new ComboboxItem();
item.Text = "year1";
item.Value = "2015";
comboBox1.Items.Add(item);

item = new ComboboxItem();
item.Text = "year2";
item.Value = "2016";
comboBox1.Items.Add(item);

comboBox1.DisplayMember = "Text";
comboBox1.ValueMember = "Value";



Step3 :点击按钮获取ComboBox的选定值


Step3: On button click get the selected value of ComboBox

private void button1_Click(object sender, EventArgs e)
{
   label1.Text = (comboBox1.SelectedItem as ComboboxItem).Value.ToString();
}


这篇关于c#windows应用程序中的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆