使用带有List的Windows窗体组合框<keyvaluepair <userenum,string>&gt; as DataSource - C#</keyvaluepair <userenum,string>

时间:2009-12-18 15:56:03

标签: c# winforms data-binding combobox

我目前正在开发一个Windows窗体GUI,我有一个Combo,我需要将一个字符串值列表显示为DisplayMembers,并使用用户定义的枚举值列表作为ValueMember。我目前正在返回一个List&gt;从我的数据库访问功能,我想将其绑定到我的组合框。我已经尝试将列表分配给.DataSource属性,将“Key”分配给.DataMember,将“Value”分配给.DisplayMember。这显然不是一种有效的方法,因为它不起作用。

有人可以给我另一种形式良好且实际有用的方法吗?

谢谢

2 个答案:

答案 0 :(得分:4)

我使用自己的类EnumPair<>和两个扩展方法将组合框与枚举类型绑定到属性。

看看这是否可以帮助您,您可以直接使用枚举。

实施后像这样使用它:

comboBox.BindToEnumValue<MyEnumType>(myBindingSourceInstance, "PropertyNameOfBindingSource");

假设您的表单上有一个名为“comboBox”的ComboBox,一个名为“MyEnumType”的Enum和一个BindingSource的实例。 PropertyNameOfBindingSource应该是BindingSource具有列表的类型的Property的名称,其PropertyType为MyEnumType。 后台工作的实现如下,不需要扩展方法,我只是不喜欢编写几乎相同的代码行; - )

public static class ComboBoxExtensions
{
    public static void BindToEnumValue<TEnum>(this ComboBox cbo, BindingSource bs, string propertyName)
    {
        cbo.DataSource = EnumPair<TEnum>.GetValuePairList();
        cbo.ValueMember = EnumPair<TEnum>.ValueMember;
        cbo.DisplayMember = EnumPair<TEnum>.DisplayMember;
        cbo.DataBindings.Add(new Binding("SelectedValue", bs, propertyName));
    }

    public static void BindClear(this ComboBox cbo)
    {
        cbo.DataSource = null;
        cbo.DataBindings.Clear();
    }
}

/// <summary>
/// Represents a <see cref="EnumPair"/> consisting of an value 
/// of an enum T and a string represantion of the value.
/// </summary>
/// <remarks>
/// With this generic class every <see cref="Enum"/> can be
/// dynamically enhanced by additional values, such as an empty
/// entry, which is usefull in beeing used with 
/// <see cref="ComboBox"/>es.
/// </remarks>
/// <typeparam name="T">The type of the <see cref="Enum"/> to represent.</typeparam>
public partial class EnumPair<T>
{
    #region Constants

    public const string ValueMember = "EnumValue";
    public const string DisplayMember = "EnumStringValue";

    #endregion

    #region Constructor

    /// <summary>
    /// Initializes a new instance of the <see cref="EnumPair"/> class.
    /// </summary>
    public EnumPair()
    {
        Type t = typeof(T);
        if (!t.IsEnum)
        {
            throw new ArgumentException("Class EnumPair<T> can only be instantiated with Enum-Types!");
        }
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="EnumPair"/> class.
    /// </summary>
    /// <param name="value">The value of the enum.</param>
    /// <param name="stringValue">The <see cref="string"/> value of the enum.</param>
    public EnumPair(T value, string stringValue)
    {
        Type t = typeof(T);
        if (!t.IsEnum)
        {
            throw new ArgumentException("Class EnumPair<T> can only be instantiated with Enum-Types!");
        }

        this.EnumValue = value;
        this.EnumStringValue = stringValue;
    }

    #endregion

    #region Properties

    /// <summary>
    /// Gets or sets the value part of the <see cref="EnumPair"/>.
    /// </summary>
    public T EnumValue { get; set; }

    /// <summary>
    /// Gets or sets the string value of the <see cref="EnumPair"/>.
    /// </summary>
    public string EnumStringValue { get; set; }

    #endregion

    #region Methods

    /// <summary>
    /// Returns a <see cref="string"/> that represents the current <see cref="EnumPair"/>.
    /// </summary>
    public override string ToString()
    {
        return this.EnumStringValue;
    }

    /// <summary>
    /// Generates a <see cref="List<T>"/> of the values
    /// of the <see cref="Enum"/> T.
    /// </summary>
    public static List<EnumPair<T>> GetValuePairList()
    {
        List<EnumPair<T>> list = new List<EnumPair<T>>();
        EnumPair<T> pair = new EnumPair<T>();

        foreach (var item in Enum.GetValues(typeof(T)))
        {
            pair = new EnumPair<T>();
            pair.EnumValue = (T)item;
            pair.EnumStringValue = ((T)item).ToString();
            list.Add(pair);
        }

        return list;
    }

    /// <summary>
    /// Implicit conversion from enum value to <see cref="EnumPair<>"/> from that enum.
    /// </summary>
    /// <param name="e">The enum value to convert to.</param>
    /// <returns>A <see cref="EnumPair<>"/> to the enum value.</returns>
    public static implicit operator EnumPair<T>(T e)
    {
        Type t = typeof(EnumPair<>).MakeGenericType(e.GetType());
        return new EnumPair<T>((T)e, ((T)e).ToString());
    }

    #endregion
}

答案 1 :(得分:0)

您可以尝试这样的事情:

ddTemplates.DataSource =
  Enum.GetValues(typeof(EmailTemplateType))
  .Cast<EmailTemplateType>().ToList()
  .Select(v => new KeyValuePair<int, string>((int)v, v.ToString())).ToList();