Thursday, February 1, 2007

Enum and DropDowns

So I need to get the name and value of an Enum to tie sensibly to a DropDownList. This is how you do it:

Enum definition:

public enum Categories
{
Wildlife,
Resorts,
Beer,
Other
}



To tie to DropDownList called ddCategory:

ddCategory.DataSource = Enum.GetNames(typeof(Categories));
ddCategory.DataBind();

To set the selected value:


ddCategory.SelectedValue = Enum.GetName(typeof(grr.Categories),1) // or just "Wildlife"

5 comments:

radical said...

This is how I do it...

public enum Categories
{
Wildlife = 0,
Resorts = 1,
Beer = 2,
Other = 3
}

To tie to DropDownList called comboBox1:

this.comboBox1.DataSource = Enum.GetValues( typeof(Categories) );


To Set a value

this.comboBox1.SelectedItem = Categories.Other;


You might also notice that I gave the enum some ids. I just find them helpfull, if I ever want to record a selection in a table somewhere.

Ranjit Thayyil said...

@radical:
I am tying to the names and not values because to the user values may not make sense. Thanks for the comment!

radical said...

Yeah but the thing about Enums is that once you assign them values, they can be easily interchanged. Number comparison is far more faster than string compare.

Ranjit Thayyil said...

@radical:
I am sure you are aware than Enums are automatically assigned numbers in the order of 0,1,2.. if its not explicitly assigned. Plus I am not too sure of using enums for values that change!

radical said...

I know... Don't get fooled by my simple example. My approach expands to enums having non sequential ID assignment.. You have a lot to learn my young padawan. :)