Reputation: 1733
Let's say I have a RadioButtonList in C#. This list contains a selector for favorite fruits (sorted alphabetically):
Favorite Fruits:
( ) Apple
( ) Banana
( ) Pineapple
( ) Pomegranate
...and let's say I have a method that prints out facts about your favorite fruit at the click of a button:
private void FruitFactsButton_OnClick(arguments){
switch( favoriteFruits.SelectedIndex ){
case 0: // Apple
doStuffForApple();
break;
case 1: // Banana
doStuffForBanana();
break;
case 2: // Pineapple
doStuffForPineapple();
break;
case 3: // Pomegranate
doStuffForPomegranate();
break;
}
}
Let's say there are dozens of switch/cases in my codebase that depend on which favoriteFruits
element is selected.
If I decide to add an element to this list (not at the end), I'd have to manually find every switch/case and update the indices (adding Banana
would force me to +1 the indices of Kiwi
, Pineapple
, and Pomegranate
, if I wanna keep everything alphabetical.)
Is there a way I can reference the indices as an enumerated value? As in, is there something that I can do that's similar to this?
switch( favoriteFruits.SelectedIndex ){
case favoriteFruits.getEnumConstants.APPLE:
doStuffForApple();
break;
I know there's a RadioButtonList.Items
accessor, but I'm stumped as to where to go from there. Any help is appreciated!
Upvotes: 1
Views: 1076
Reputation: 17118
Is there a way I can reference the indices as an enumerated value?
Based on your entire post it seems that, "you need to know what is clicked and take action(s) based on that". It really doesn't matter then if you will be testing against the index or the value of the control. If that's the case then doing the following should help:
// declare the items, no need to set values
public enum FavoriteFruits {
Banana,
Apple, }
// bind the enum to the control
RadioButtonList1.DataSource = Enum.GetValues(typeof(FavoriteFruits));
RadioButtonList1.DataBind();
// this is needed because SelectedValue gives you a string...
var selectedValue = (FavoriteFruits)Enum.Parse(typeof(FavoriteFruits),
RadioButtonList1.SelectedValue, true);
//...then you can do a switch against your enum
switch (selectedValue )
{
case FavoriteFruits.Apple:
doStuffForApple();
break;
case FavoriteFruits.Banana:
doStuffForBanana();
break;
}
Make sure to validate the SelectedValue
as it will throw an exception if nothing is selected.
Upvotes: 2
Reputation: 45500
If I understood correctly, you would use enums?
enum Fruits{
Apple = 0,
Banana = 1,
Pineapple = 2,
Pomegranate = 3
};
switch( favoriteFruits.SelectedIndex ){
case Fruits.Apple:
doStuffForApple();
break;
Upvotes: 0