3

In my project there is an UI which contains a combobox and the combobox will list some communication protocol, such as TCP/IP, FTP and so on

I want to use an enum to present the communication protocols, maybe like this:

public enum CommuProtocol 
{
   TCPIP = 0,
   FTP,
   MPI,
   Other
}

so, how to bind the enum value to the text in combobox. For example, from the text selected in combobox I can easily know the corresponding enum value and vice versa. And I hope that will be easy to be extended in the future.

The text maybe not the same with the enum value, etc, TCP/IP vs TCPIP...

Thanks!

Carlos Liu
  • 2,348
  • 3
  • 37
  • 51

3 Answers3

5

Well, either you make a function which translates the values into strings or you ToString the value:

CommuProtocol prot = CommuProtocol.FTP;
string name = prot.ToString();

You can use the name of the enum member to get a proper value with the parse member of Enum:

CommuProtocol prot = System.Enum.Parse(CommuProtocol, "FTP");

However, since the names of the members might not be suitable for display it's possible that you'll end up making a method that translates the names anyway.

Skurmedel
  • 21,515
  • 5
  • 53
  • 66
  • the prolbem is: the enum value is not the same with text, such as TCP/IP and TCPIP – Carlos Liu Jan 14 '10 at 09:01
  • Nice solution to use the ToString(), I was going to suggest the old C/C++ way of delaring an array of strings and using the enum as the index. I'm glad you replied before I did! – Tony Jan 14 '10 at 09:01
  • Hehe thanks. I've had to do this quite a lot of times myself. Carlos: if you can't use the names, you'll have to devise a way to translate "TCP/IP" into "TCP" or the reverse. It could be as simple as a method with a big switch-statement in it. You are not using WPF are you? There is a more elegant way if so. – Skurmedel Jan 14 '10 at 09:06
  • You are not using WPF are you? ------------------ No :-( – Carlos Liu Jan 14 '10 at 09:11
  • 1
    Nothing wrong with a switch to output the correct name. It is there for a reason! – Ed S. Jan 15 '10 at 02:23
  • Indeed... that or store it in a small table which maps them. Net result is the same. – Skurmedel Jan 15 '10 at 11:22
2

You should go with Enum.GetValues() method. Here is an example: How do you bind an Enum to a DropDownList control in ASP.NET?

Community
  • 1
  • 1
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
2

This gets asked a lot. See the answers here.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009