CodersAdvocate

I work hard, so you don't have to

Enum to Bindable object

 
Enums are a very powerful alternative to look up tables in SQL. Using C# you cannot directly bind an enumerator to the datasource of an object (drop down list).

The below code will allow you to do this.
Enjoy..............!

public static DataTable EnumToBind(Type typeofEnum)
        {
            string[] enumNames = Enum.GetNames(typeofEnum);
            Array enumValues = Enum.GetValues(typeofEnum);
            var table = new DataTable();
            DataColumn column;

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "value";
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "name";
            table.Columns.Add(column);

            for (int i = 0; i < enumNames.Length; i++)
            {
                DataRow dr = table.NewRow();
                dr["name"] = enumNames[i];
                dr["value"] = enumValues.GetValue(i);
                table.Rows.Add(dr);
            }

            return table;
        }
Copyright 2011 CodersAdvocate ©