Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox bound to an enum type's values while also having a "blank" entry?

If I bind a WinForms ComboBox to an enum type's values, i.e.

combo1.DropDownStyle = ComboBoxStyle.DropDownList;
combo1.DataSource = Enum.GetValues(typeof(myEnumType));

Who knows how I could achieve the same result, while, in addition to entries matching each enum value, I can also have a blank entry representing no selection?

I cannot simply add a special value to the enum type because this must be flexible to deal with any enum type.

I'd appreciate your help.

Edit: I should make clear that I want to bind the actual enum values and not their names. If the actual enum values are bound, the ComboBox takes care of calling their ToString() to get the text to display.

like image 208
xyz Avatar asked Feb 28 '23 19:02

xyz


1 Answers

Not sure if you guys have tried all of the code that you've been posting or not, but you can't add items do a databound ComboBox. This is winforms, not WPF, so there is no "DataBind" function.

You could do this:

public static string[] GetEnumValues<T>(bool includeBlank) 
{
    List<string> values = new List<string>((Enum.GetValues(typeof(T)) as T[]).Select(t => t.ToString()));

    if (includeBlank)
    {
        values.Insert(0, string.Empty);
    }

    return values.ToArray();
}

Then

combo.DataSource = GetEnumValues<myEnumType>(true);
like image 102
Adam Robinson Avatar answered Apr 25 '23 19:04

Adam Robinson