0
votes

I've a problem with my new application:

I've set the DataSource of a ComboBox to an enum, so the ComboBox displays all the members of the enum. Good!

But now I want to change the displayd text, but not the value of the ComboBox.

Here is the DataSource set:

CbCategory.DataSource = Enum.GetValues(typeof (ConversionCategories.Categorys));

And this is the enum:

public enum Categorys
    {
        Acceleration,
        Area,
        Energy,
        Frequency,
        Length,
        Mass,
        Time,
        Velocity,
        Volume,
    }

And now for example I want "Velocity" is displayd as "Speed", but the value mustbe the same.

P.S: I don't use WPF.

3

3 Answers

1
votes

You could create a dictionary that maps each enum value to a display string and use that dictionary as the data source for the combo box:

SortedDictionary<Categorys, string> catergoryDictionary = new SortedDictionary<Categorys, string>
{
    {Categorys.Acceleration, "Acceleration"},
    {Categorys.Area, "Area"},
    {Categorys.Velocity, "Speed"}
};

CbCategory.DataSource = new BindingSource(catergoryDictionary, null);
CbCategory.ValueMember = "Key";
CbCategory.DisplayMember = "Value";
1
votes

Please Use Dictionary.

Dictionary<Categorys, string> catergoryDisplay = new Dictionary<Categorys, string>
    {
        {Categorys.Velocity, "Speed"}
    };

    CbCategory.DataSource = new BindingSource(catergoryDisplay , null);
    CbCategory.ValueMember = "Key";
    CbCategory.DisplayMember = "Value";

Please try this code.

0
votes

If the value has only to be castable to Categorys you can do the following:

public enum Categorys
{
    Acceleration,
    Area,
    Energy,
    Frequency,
    Length,
    Mass,
    Time,
    Velocity,
    Volume
}

private static readonly string[] DisplayNames = new string[]
{
    "Acceleration",
    "Area",
    "Energy",
    "Frequency",
    "Length",
    "Mass",
    "Time",
    "Speed",
    "Volume"
};

private class CategoryItem
{
    private Categorys Category;
    private string DisplayName;

    public CategoryItem(Categorys category, string display_name)
    {
        Category = category;
        DisplayName = display_name;
    }

    public override string ToString()
    {
        return DisplayName;
    }

    public static implicit operator Categorys(CategoryItem item)
    {
        return item.Category;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    List<CategoryItem> items = new List<CategoryItem>();
    int i = 0;

    foreach (var category in Enum.GetValues(typeof(Categorys)))
        items.Add(new CategoryItem((Categorys)category, DisplayNames[i++]));

    CbCategory.DataSource = items;
}

A possible way to access the value is then:

Categorys category = (Categorys)(CategoryItem)CbCategory.SelectedItem;

Maybe you can wrap this in a getter or some class method like:

public Categorys SelectedCategory
{
    get { return (Categorys)(CategoryItem)CbCategory.SelectedItem; }
}