0

I have a namespace in which I have declared an enum as follows:

namespace IXMSoft.Business.SDK.Data
{
using System;

public enum BaudRate
{
    BR115200 = 7,
    BR19200 = 4,
    BR230400 = 8,
    BR2400 = 1,
    BR38400 = 5,
    BR4800 = 2,
    BR57600 = 6,
    BR9600 = 3
  }
}

When I retrieve these values in a combo box, which is in another namespace, using the statement

comboBox1.Items.Add(BaudRate.BR5700);

it shows the value as for example

"BR5700"

I want to remove BR in front and just want to display the value as "5700". What should I do?

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
Ankur Sharma
  • 283
  • 2
  • 13
  • need to use `Replace` mmethod – Rahul May 27 '13 at 07:06
  • Get the string before you add it into ComboBox1.String str=BaudRate.BR5700; if(str.contains("BR")) str=str.replace("BR","");Hope it helps you. – MahaSwetha May 27 '13 at 07:06
  • possible duplicate of [How do I have an enum bound combobox with custom string formatting for enum values?](http://stackoverflow.com/questions/796607/how-do-i-have-an-enum-bound-combobox-with-custom-string-formatting-for-enum-valu) – nawfal Jun 08 '13 at 22:54

5 Answers5

4

use the DescriptionAttribute and an appropriate extension method to read it out.

public enum BaudRate
{
    [Description("115200 kb")]
    BR115200 = 7,
    [Description("19200 kb")]
    BR19200 = 4,
    [Description("230400 kb")]
    BR230400 = 8,
    [Description("2400 kb")]
    BR2400 = 1,
    [Description("115200 kb")]
    BR38400 = 5,
    [Description("4800 kb")]
    BR4800 = 2,
    [Description("57600 kb")]
    BR57600 = 6,
    [Description("9600 kb")]
    BR9600 = 3
}

The extension method:

public static class EnumExtension
{
    /// <summary>
    /// Gets the string of an DescriptionAttribute of an Enum.
    /// </summary>
    /// <param name="value">The Enum value for which the description is needed.</param>
    /// <returns>If a DescriptionAttribute is set it return the content of it.
    /// Otherwise just the raw name as string.</returns>
    public static string Description(this Enum value)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        string description = value.ToString();
        FieldInfo fieldInfo = value.GetType().GetField(description);
        DescriptionAttribute[] attributes =
           (DescriptionAttribute[])
         fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
        {
            description = attributes[0].Description;
        }

        return description;
    }

    /// <summary>
    /// Creates an List with all keys and values of a given Enum class
    /// </summary>
    /// <typeparam name="T">Must be derived from class Enum!</typeparam>
    /// <returns>A list of KeyValuePair&lt;Enum, string&gt; with all available
    /// names and values of the given Enum.</returns>
    public static IList<KeyValuePair<Enum, string>> ToList<T>() where T : struct
    {
        var type = typeof(T);

        if (!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }

        return (IList<KeyValuePair<Enum, string>>)
                Enum.GetValues(type)
                    .OfType<Enum>()
                    .Select(e => new KeyValuePair<Enum, string>(e, e.Description()))
                    .ToArray();
    }

    public static T GetValueFromDescription<T>(string description) where T : struct
    {
        var type = typeof(T);

        if(!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }

        foreach(var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;

            if(attribute != null)
            {
                if(attribute.Description == description)
                {
                    return (T)field.GetValue(null);
                }
            }
            else
            {
                if(field.Name == description)
                {
                    return (T)field.GetValue(null);
                }
            }
        }

        throw new ArgumentOutOfRangeException("description");
        // or return default(T);
    }
}

At the and you can simply apply this to your combo box by calling:

var list = EnumExtension.ToList<BaudRate>();
myComboBox.DataSource = list;
myComboBox.ValueMember = "Key";
myComboBox.DisplayMember = "Value";
Community
  • 1
  • 1
Oliver
  • 43,366
  • 8
  • 94
  • 151
  • +1: much better than the hacks used in other answers, which are specific to this enum. – It'sNotALie. May 27 '13 at 08:01
  • @newStackExchangeInstance Agreed (quite fond of this answer), but OP did mention in another post that he was unable to modify the code for the enum. – Levi Botelho May 27 '13 at 08:17
  • @newStackExchangeInstance: What if i dont have the desctiption tag? Is it still possible to show the value without BR? – Ankur Sharma May 27 '13 at 11:08
  • @LeviBotelho: I can't make changes in the file as it is protected. Also the file does not have description tag. Is there a way to do localization? – Ankur Sharma May 27 '13 at 11:09
  • @Ankur You could make a wrapper class with an overriden ToString. – It'sNotALie. May 27 '13 at 14:02
  • 1
    @AnkurSharma: If the file is protected there won't be any changes in the future. So you could also define your own enum `BetterBaudRate` that simply uses the same integer value for each baud rate. If you need to provide anywhere something of type `BaudRate` than simply cast it `BaudRate br = (BaudRate)myBetterBaudRate`. – Oliver May 27 '13 at 14:51
2

Example with string.replace:

BaudRate.BR115200.ToString().Replace("BR","");

Example with substring:

BaudRate.BR115200.ToString().Substring(2);
Ted
  • 3,985
  • 1
  • 20
  • 33
2

Removing the BR from the enum names seems like the most logical course of action. Given that your enum itself is named BaudRate, the BR is redundant. And given that it is present on every value, it doesn't add any descriptive power to the value name. And given that an enum value is always prefixed by the enum name, the result will always be clear (BaudRate.9600 instead of BaudRate.BR9600).

If you can't/don't want to do this then you need to run a BaudRate.XXX.ToString().Substring(2) on each value before adding in order to remove the first two characters.

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
1
public enum BaudRate
{
    BR115200 = 7,
    BR19200 = 4,
    BR230400 = 8,
    BR2400 = 1,
    BR38400 = 5,
    BR4800 = 2,
    BR57600 = 6,
    BR9600 = 3
  }
}

foreach (string name in Enum.GetNames(BaudRate))
{
    cmbEnum.Items.Add(name.Replace("BR",""));
}
Furkan Ekinci
  • 2,472
  • 3
  • 29
  • 39
0

Have your combobox defined like as shown below :

<combobox>
   <ComboBoxItem>--</ComboBoxItem>
   <ComboBoxItem>2400</ComboBoxItem>
   <ComboBoxItem>4800</ComboBoxItem>
   <ComboBoxItem>9600</ComboBoxItem>
   <ComboBoxItem>19200</ComboBoxItem> // and soo on
</combobox>

and bind your Enum to the combobox

Vikram
  • 1,617
  • 5
  • 17
  • 37