tags:

views:

321

answers:

4

How can I bind a DataSource with some selected enum values?

My Enum:

public enum Filters : byte
{
    Filter1 = 1,
    Filter2 = 2,
    Filter3 = 4,
    Filter4 = 8,
    Filter5 = 16
}

Selected values:

public Filters SelectedFilters = Filters.Filter1 | Filters.Filter4;

How can I bind the SelectedFilters variable as a datasource?

A: 

This article Enumeration Binding shows one way to accomplish this.

Mitch Wheat
A: 

Using:

public enum Filters : byte
{
    Filter1 = 1,
    Filter2 = 2,
    Filter3 = 4,
    Filter4 = 8,
    Filter5 = 16
}

And selecting some values:

public Filters SelectedFilters = Filters.Filter1 | Filters.Filter4;

I created a method that can solve my own question:

public static List<T> EnumToList<T>(Enum someEnum)
{
    List<T> list = new List<T>();

    foreach (var it in Enum.GetValues(someEnum.GetType()))
    {
        if ((Convert.ToByte(it) & Convert.ToByte(someEnum)) != 0)
        {
            list.Add((T)it);
        }
    }

    return list;
}


myRepeater.DataSource = EnumToList<Filters>(SelectedFilters);
Zanoni
A: 

If you want to be able to have the Text and Value of the DropDownList seperate, use a Ditionary like this:

    public static Dictionary<int, string> EnumToList(Type t)
    {
        Dictionary<int, string> list = new Dictionary<int, string>();

        foreach (var v in Enum.GetValues(t))
        {
            list.Add((int)v, Enum.GetName(t, (int)v));
        }

        return list;
    }
A: 

To use it, in the case of a LinqDataSource Selecting event:

protected void ldsMyTypes_Selecting(object sender, LinqDataSourceSelectEventArgs e) { e.Result = EnumToList(typeof(Enums.FeedTypes)); }