首页 > 解决方案 > 尝试将组合框绑定到 C# 中的枚举

问题描述

我有一个包含枚举属性的类:

public RaTypes RaBucket1Type { get; set; }

我的枚举是:

    public enum RaTypes
{
    Red,
    Yellow
}

我能够将表单的组合框数据源绑定到枚举,这样当我单击下拉列表时,我会看到枚举:

cmbBucket1Type.DataSource = Enum.GetValues(typeof(RaTypes));

当我加载表单时,我想用现有值填充组合框。我尝试了以下方法:

        cmbBucket1Type.DisplayMember = "TradeType";
        cmbBucket1Type.ValueMember = "TradeEnumID";
        cmbBucket1Type.SelectedValue = EditedAlgorithm.RaBucket1Type;

但这没有用。

另外,我不确定我是否正确实现了 ValueChanged 事件处理程序:

EditedAlgorithm.RaBucket1Type = (RaTypes)((ComboBox)sender).SelectedItem;

有人可以帮我理解:

  1. 如何将组合框设置为当前值,以及
  2. 如何处理事件处理程序,以便我可以将属性设置为选择的任何内容?

谢谢-埃德

我试过的更新

    cmbBucket1Type.SelectedIndex = cmbBucket1Type.FindString(EditedAlgorithm.RaBucket1Type.ToString());

    cmbBucket1Type.SelectedItem = EditedAlgorithm.RaBucket1Type;

两者都不起作用。

标签: c#combobox

解决方案


我认为您使用的术语与正常情况略有不同,这使其难以理解。

通常,术语AddPopulateSelect用于表示以下含义:

  • 添加 - 将一个项目添加到组合框中的现有项目集。
  • 填充 - 使用一组项目初始化组合框。
  • 选择(显示) - 在组合框中的众多项目中选择一项作为选定项目。通常该项目将显示在组合框可见区域中。

清除后,我认为以下是您想要做的。

  1. 最初用一组值填充。ComboBox在您的情况下, 的值RaType Enum
  2. 创建一个包含上述属性的类的实例。由于您没有命名该类,因此我将简单地命名它SomeClass
  3. 使用您选择的值初始化RaBucket1Type所述类实例的属性。enum我将它初始化为Yellow.
  4. 在启动时ComboBox 选择所述值。
  5. 之后Form_Load,在任何给定时间,如果用户更改 的值,ComboBox则更改会反映在您的类实例属性中。

为此,我会做这样的事情:

public partial class MainForm : Form
{
    // Your class instance.
    private SomeClass InstanceOfSomeClass = null;

    public MainForm()
    {
        InitializeComponent();
        // Initialize the RaBucket1Type property with Yellow.
        InstanceOfSomeClass = new SomeClass(RaTypes.Yellow);
        // Populating the ComboBox
        comboBox1.DataSource = Enum.GetValues(typeof(RaTypes));
    }

    // At selected index changed event
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Get the selected value.
        var selected = comboBox1.SelectedValue;
        // Change the `RaBucket1Type` value of the class instance according to the user choice.
        InstanceOfSomeClass.RaBucket1Type = (RaTypes)selected;
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        // At form load time, set the `SelectedItem` of the `ComboBox` to the value of `RaBucket1Type` of your class instance.
        // Since we initialized it to `Yellow`, the `ComboBox` will show `Yellow` as the selected item at load time.
        if (InstanceOfSomeClass != null)
        {
            comboBox1.SelectedItem = InstanceOfSomeClass.RaBucket1Type;
        }
    }
}

public enum RaTypes
{
    Red,
    Yellow
}

public class SomeClass
{
    public RaTypes RaBucket1Type { get; set; }

    public SomeClass(RaTypes raTypes) { RaBucket1Type = raTypes; }
}

请记住,这是一个基本示例,向您展示如何处理这种情况,而不是完整的完成代码。您需要进行大量错误检查以确保类实例和选定项不为空等。


推荐阅读