views:

26

answers:

2

Hi,

I'm using a Bitwise Enum as a Datasource for a repeater control in which each line has a checkbox. When the user saves data, enum values corresponding to the checked boxes are saved into a single database field.

However, when the user comes to edit the data, obviously I need to pre-populate the repeater with the existing values. I can do this in a straightforward value by interating through the possible values of the enum and checking boxes accordingly. However, ideally I'd really like my code to remain independent of changes to the data: so if I change the or add to the values in the Enum, my code will still work without changing the code in my control.

It seems the obvious thing to do is try to iterate through the existing values in the enum field once I've got it back from the database. In other words, if the saved value corresponds to two selections out of the several in the enum, I need to loop through just those two. However I can see no method or property that I can use to do this. Can anyone point me in the right direction?

A sample ... which might help make sense of this ... is that I can get sort of the effect I want by casting it to a string and splitting it, but it's clumsy (comsPrefs is the enum in question)

        Dim selectedPrefs As String = comsPrefs.ToString()
        Dim splitStr() As String = selectedPrefs.Split(","c)
        Dim i As Integer

        For i = 0 To splitStr.Length - 1
            'do some cool stuff
        Next

Cheers, Matt

A: 

To get all the values of an enumeration use Enum.GetValues(typeof(myEnumeration)).

System.Enum has other methods that will allow you to get the identifiers (names) and convert named to/from values.

NB. Unless every different value has a distinct unique bit pattern (i.e. there are no two distinct subsets that when combined with bitwise-or have the same value), some of the conversions will be ambiguous.

Richard
Thanks, but I don't need all the possible values. I just need the saved values. So imagine my enum is say apples = 1, oranges = 2, pears = 4 and the value saved for a particular row is 3 (apples OR oranges) .. I need to iterate through the potential values of what's saved, i.e. apples, oranges. Does that make sense?
Matt Thrower
+1  A: 

Something like this?

[Flags]
public enum YourEnum
{
    One = 1, Two = 2, Four = 4, Eight = 8
}

// ...

YourEnum exampleData = YourEnum.Two | YourEnum.Four;

var values = Enum.GetValues(typeof(YourEnum))
                 .Cast<YourEnum>()
                 .Where(x => exampleData.HasFlag(x));

foreach (var v in values)
{
    Console.WriteLine(v);
}

Note that the HasFlag method is only available in .NET 4 -- if you're using an earlier version of the framework then you'll need to use Where(x => (exampleData & x) == x) instead.

LukeH
nice, thanks. I'm still not familiar enough with linq/lambda to think of it as a solution!
Matt Thrower