 |
|
 |
Another trick:
Fill the .Items collection of a drop down list with the Names and Values of an Enum.
Note that
a) the values of the Enum are not sequential (11, 21, etc.)
b) “Option Strict” is “On”, so the conversion between “system.array” (returned by the Enum.GetValues) and “1-dimensional array of integer” (used to store the names and to set the Item.Text) is an explicit conversion; with “Option Strict Off” that would not be necessary.
Hope you enjoy.
If someone knows some better way, please let me know too.
Hug,
Pedro Pereira
----------------------------------------------------------------------------------
Option Strict On
----------------------------------------------------------------------------------
Enum TipoConsulta
Codigo = 11
SubCodigo = 21
Descricao = 31
Banco = 41
Tipo = 51
CodOcorrencia = 69
IdPortador = 77
End Enum
----------------------------------------------------------------------------------
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
' Rotina que monta os itens de uma drop down list
' setando o .value e o .text a partir de um Enum cujos valores não são sequenciais
If Not IsPostBack Then
Dim arrValoresEnum() As Integer
' o ctype abaixo é necessário para fazer a conversão de 'system.array'
' para() '1-dimensional array of integer'
' a conversão tem de ser explícita, pois estou usando option strict,
' caso contrário não seria necessário
arrValoresEnum = CType([Enum].GetValues(GetType(TipoConsulta)), Integer())
Dim arrNomesEnum() As String
arrNomesEnum = [Enum].GetNames(GetType(TipoConsulta))
Dim meuInd As Integer = 0
Do While meuInd < arrValoresEnum.Length
Dim meuItem As New ListItem
meuItem.Value = CStr(arrValoresEnum(meuInd))
meuItem.Text = arrNomesEnum(meuInd)
ddlEnum.Items.Add(meuItem)
meuInd += 1
Loop
End If
End Sub
----------------------------------------------------------------------------------
|
|
|
|
 |
|
 |
I think that I didn't quite unterstanded that point - 'How to retrieve an Enum member given its name'.
Why should I have to use "parse" and so on?
Why not just use the Enum like an Integer - what, in fact, it is?
Try the sample below, it works:
Enum TipoConsulta
Codigo = 11
SubCodigo = 21
Descricao = 31
Banco = 41
Tipo = 51
CodOcorrencia = 69
IdPortador = 77
End Enum
...
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' Aqui trato o Enum como um inteiro - sem problemas! (here I use my enum like an integer - without problem!)
Dim meuInt As Integer
meuInt = TipoConsulta.Descricao + TipoConsulta.Tipo
Response.Write(CStr(TipoConsulta.Descricao) & " mais " & CStr(TipoConsulta.Tipo) & " igual a" & CStr(meuInt))
End Sub
Can you help me?
What I an not seeing?
Thanks,
|
|
|
|
 |
|
 |
Because you may have the string, rather than have the number.
Christian Graus - Microsoft MVP - C++
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
 |
|
 |
Christian,
I an grateful for your atention, but..
No, that didn't happens, you always get the integer value.
It is showed in the code that I have sended.
Take a look at the answer from Alberto Venditti.
Anyway, thanks for you kindness.
|
|
|
|
 |
|
 |
I try to explain the need 'to retrieve an Enum member given its name'; for example, think about a configuration file where you want to store/retrieve some settings of yours in a mnemonic, verbose, user-friendly way, as in: <appSettings> <add key="TipoConsulta1" value="Descricao" /> </appSettings> instead of: <appSettings> <add key="TipoConsulta1" value="31" /> </appSettings> Hope this helps, AV
|
|
|
|
 |
|
 |
Yes, of course.
In that context, I can see the utility.
Thanks!
|
|
|
|
 |
|
 |
Just a heads up, you cannot reliably use the `IsDefined` method with an enumeration inheriting from the `Flags` attribute.
For Example:
Enum.IsDefined(typeof(NotifyFilters), 1); // Returns true, which is correct
Enum.IsDefined(typeof(NotifyFilters), 4096); // Returns false, which is correct
Enum.IsDefined(typeof(NotifyFilters), 1+2); // Returns false, which is INCORRECT
System.IO.NotifyFilters
Specifies changes to watch for in a file or folder.
|
|
|
|
 |
|
 |
I am developing a shopping cart application for jwellary designing \
now i am displaying all the product in the table dynamically.
and also show on image button as a add to cart after every item.
now when ever client clicks on the add to cart button than i want the item id no in the button's click event's how can be it possible.
Here i show the code
System.Web.UI.WebControls.ImageButton add = new System.Web.UI.WebControls.ImageButton();
add.CssClass = "button";
//add.CommandArgument = c.getRecord(start, "Prod_ID").ToString();
add.ImageUrl = @"D:\Tarun\Final\Admin\Images\\addtocart4.jpg";
add.Click += new ImageClickEventHandler(btnaddprod_Click);
System.Web.UI.WebControls.Panel p = new System.Web.UI.WebControls.Panel();
p.Controls.Add(add);
protected void btnaddprod_Click(object sender, EventArgs e)
{
//Dim cmdArg As String = CType(sender, ImageButton).CommandArgument
//I know above line is working in VB.NET but i want same thing in C#.NET can anybody helpme
}
|
|
|
|
 |
|
 |
Your question is completely out of the scope of this article.
Please, post it somewhere else.
Thank you, AV
|
|
|
|
 |
|
 |
I have not tested this in C#, but in VB.NET, if you want to use a keyword in a enum all you have to do is put the word in square brackets [GET] is an example I had at one point. When using the GetNames routine that gives you the names from the enum, it will return this one without the brackets.
|
|
|
|
 |
|
 |
The best point in my opinio is getting the Value of the Enum from the single String.
If you uses a Enum to Enumerate the DataBaseConnections to evoid harcoding with the EnterpriseLibrary... or any of this things...
It is interesting to be able to recover the value of the Enum when you already has the Instace
Ricardo Casquete
|
|
|
|
 |
|
 |
Is there a way to do the same thing but using DirectCast?
Only reason I ask is because of performance.
Ctype() has about a 100 lines of code and
DirectCast() has about 3.
Donny V.
|
|
|
|
 |
|
 |
As far as I know, DirectCast operates on reference types only.
And Enums are value types indeed...
AV
|
|
|
|
 |
|
 |
I'd like to add an Enum item with a space in the string, for example
Public Enum DocTypes
{
Brochure = 1
GraphicDesign = 2
}
Is there a way to declare GraphicDesign to "Graphic Design", (with a space added between Graphic and Design) ???
Thank you
|
|
|
|
 |
|
 |
I frankly think that it's not possible at all. Because any enum item name is a "member", so it has to follow the naming rules for variables and class members in general.
Being part of the code, these names must not contain blanks, because of the parsing rules of the C# compiler, that would not consider a two-words name as a single language token.
If the problem is related just to code readability, good alternatives are in the use of camel casing or underscores.
But I imagine that your question is related to some use of the enum item name in the user interface, for example by directly converting the enum member name in something readable by the user. If it is the case, I simply suggest you the adoption of underscores, followed by the replacement of "_" in blanks in the UI rendering phase.
About naming convetions in general (but not about your specific problem), I found also interesting this chat:
http://msdn.microsoft.com/chats/transcripts/net/design_naming_conven_012605.aspx[^]
'bye, AV
|
|
|
|
 |
|
 |
Here's how I did it like the other poster said. This returns an arraylist that I can use for a dropdown.
Public Shared Function GetStyles() As ArrayList
Dim myAL As New ArrayList
Dim names As String() = System.Enum.GetNames(GetType(Style))
For i As Integer = 0 To names.Length - 1
myAL.Add(Replace(names(i), "_", " "))
Next
Return myAL
End Function
|
|
|
|
 |
|
 |
I have found this sample code: Sample here[^]
It is not limited to variable naming conventions and can return any string and provides visually more acceptable code. However, converting from string to enum member is not possible.
|
|
|
|
 |
|
 |
If I have this enum:
Alpha = 1
Beta = 2
Gamma = 4
And I have a integer = 6, it should then represent both Beta and Gamma, how do I do this in VB.NET?
In VB6 I just used the And operator?
|
|
|
|
 |
|
 |
Normally, when you want to use Enum values in an additive way (as a bit mask), you have to declare the Enum itself with the FlagsAttribute attribute:
Public Enum MyEnum
Alpha = 1
Beta = 2
Gamma = 4
BetaAndGamma = 6
End Enum
Anyway, to combine Enum values in VB.NET, simply use the OR operator.
For example, if you have:
Dim a As MyEnum = MyEnum.Beta Or MyEnum.Gamma
the expression: a.ToString()
evaluates to: "BetaAndGamma"
|
|
|
|
 |
|
|
 |
|
 |
Use of the [Flags] attribute for enums that represent bitmasks.
[Flags] public enum Fields
{
Firstname = 0x0001
Lastname = 0x0002
Adress = 0x0004
Phone = 0x0008
}
Fields myFields = Fields.Firstname | Fields.Lastname;
Have a look at my latest article about Object Prevalence with Bamboo Prevalence.
|
|
|
|
 |
|
 |
Under various circumstances. By default Enum values start at 0. So unless there is a sensible "default" value you should always specify a non-zero value. But you do not need to specify all of the values as in your example, just the first. And a value of 1 will do, but random starting values like 293 will trap some errors if Enums ever get confused.
Anthony
|
|
|
|
 |
|
 |
Since you decribe how to test if a certain value is part of an enum, I think you could add a a description of Enum.GetValues() to your article.
It comes very handy when you have to be sure to get all possible enum values, even if the available values change over time.
Before I found this static member I actually hard-coded enum values in an array (;P what else can you do?), which leads to increased maintenance costs...
By now I've converted all these places to Enum.GetValues() and can be sure I've always got all the possible values in the array.
|
|
|
|
 |
|
 |
I was thinking the exact same thing and here is an example of how to do it:
foreach ( string s in Enum.GetNames(GetType(System.Drawing.KnownColor) )
{
Response.Write( s );
}
www.publicvoid.dk
|
|
|
|
 |
|
 |
This might be a bit off-topic, but I find it a useful hint:
When is use enumerations that are similar, or derived from each other, I set one base-enumeration, and use it's values to assign the values to the assigned enumration, so I don't have to worry about what values are used in my database etc (where of course I store only the numeric value)
For example:
A general language enumeration I use for multiple projects:
vb:Public Enum Language
English = 1
Dutch = 2
....etc
End Enum
And a specific enumeration for the languages I use on a specific website:
vb:Public Enum Sitelanguage
English = Language.English
Dutch = Language.Dutch
End Enum
This way, I can use Sitelanguage as a language on my website, an use functionality like Sitelanguage.GetValues, while still allways having a reference to my single Common Language enumeration.
Useful or complete bollocks?
|
|
|
|
 |