【问题标题】:Where (which file) to add code to handle passing enum data to combobox?在哪里(哪个文件)添加代码来处理将枚举数据传递到组合框?
【发布时间】:2014-04-18 23:20:07
【问题描述】:

我正在创建一个简单的用户注册表单,其中包含用于输入 first namelast nameuser namepassword 的字段,以及用于 majorconcentration 的两个组合框下拉列表。
我相信我了解如何将枚举数据传递给ComboBox,但不确定在哪里(同时文件)添加代码。
我要双击ComboBox 并将其添加到那里吗?
我是否要创建另一个类,添加枚举数据和代码以在组合框中显示该数据?

我相信我找到了添加的方法,这是我的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public enum MajorList { Engineering = 1, Science, Humanities, Art, Business };
    public enum EngConcentrations { Mechanical = 1, Electrical, Chemical, Civil };
    public enum SciConcentrations { Computer, Biology };
    public enum HumConcentrations { English, History };
    public enum ArtConcentrations { Graphics, Painting, History, Music };
    public enum BusConcentrations { Administration, Economics, Accounting };

    private void Form1_Load_1(object sender, EventArgs e)
    {
        foreach (var item in Enum.GetValues(typeof(MajorList)))
        {
            majors.Items.Add(item);
        }            
    }
}

是否可以根据我选择的专业添加其他枚举之一? 例如,我选择工程,第二个组合框会有工程浓度的下拉菜单?

【问题讨论】:

  • 嗨@GrantWinney 我添加了将专业添加到组合框中的代码。如果您能提供帮助,我在最后添加了一个后续问题。再次感谢。

标签: c# winforms combobox enums


【解决方案1】:

看来您解决了最初的问题。该代码将添加您想要的值,并将其放置在表单的 Load 事件中就可以了。

至于第二个问题,是的,您可以根据“主要”ComboBox 中选择的值切换第二个ComboBox。订阅SelectedValueChanged 事件:

void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
    var selectedMajor = (MajorList)comboBox1.SelectedItem;

    switch (selectedMajor)
    {
        case MajorList.Art:
            // populate the second combo box with ArtConcentrations values
            break;

        case MajorList.Business:
            // populate the second combo box with BusConcentrations values
            break;

        ...
}

【讨论】:

  • 非常感谢第二个组合框的帮助。你说过,“把它放在表单的 Load 中就可以了。”是否有不同的区域放置它,或者我可以自己创建一个新事件来添加值?
猜你喜欢
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 2013-02-09
  • 2016-06-18
  • 1970-01-01
相关资源
最近更新 更多