26332 total geeks with 3498 solutions
Recent challengers:
  • krc bonus 12 - 08:08AM
  • krc bonus 11 - 08:00AM
  • KNL reverser 7 - 07:52PM
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: Jun 30
June Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Out with a bang:
The Last of Us lets
PS3 exit with head
held high
EU Justice
Department stalls
India"s security
clearance
Nuke plants to keep
PDP-11 UNTIL 2050!
COLD BALLS OF FLAME
light up
International Space
Station
Google erases G8
venue from Earth:
Microsoft doesn"t
Chinese hackers
launch PRISM scare
campaign
Spear phish your
boss to win more
security cash
Six nations ask
Google for answers
on Glass privacy
Huawei muses on
Nokia"s future
House bill: "Hey
NASA, that asteroid
retrieval plan?
Fuggedaboutit"
Slashdot
Revisiting Amdahl"s
Law
Altering Text In
eBooks To Track
Pirates
NVIDIA To License
Its GPU Tech
MySQL Man Pages
Silently Relicensed
Away From GPL
Verizon Accused of
Intentionally
Slowing Netflix
Video Streaming
Oculus Rift Raises
Another $16 Million
KWin Maintainer:
Fanboys and Trolls
Are the Cancer
Killing Free
Software
Google Files First
Amendment Challenge
Against FISA Gag
Order
Microsoft To Start
Dumping Surface RT
To Schools For $199
With an Eye Toward
Disaster, NYC
Debuts Solar
Charging Stations
Article viewer

Using an Enumeration as a Data Source for Binding, v.2.0



Written by:dbirdz
Published by:Nightscript
Published on:2009-07-25 07:27:18
Topic:Dot.Net
Search OSI about Dot.Net.More articles by dbirdz.
 viewed 8222 times send this article printer friendly

Digg this!
    Rate this article :
This is an extension of the code written by Gimlock published on 2005-07-22, with some issues of inflexibility addressed. Additionally it supports not only WinForm ListControls, but also WebForm ListControls.

The code given below can be directly included in a project. It gives you the possibility to:

  • bind a combo box or list box to an enum (WinForms -> EnumBinder class)
  • bind a dropdown list to an enum (WebForms -> WebEnumBinder class)
  • bind only a subset of the enum item to the list control (use Array objValues parameter)
  • modify how the item is displayed (use StringPrint.Underscores, StringPrint.CamelCase)


The original code from gimlock can be found at http://www.osix.net/modules/article/?id=715. This code is heavily inspired by the work of gimlock.

In the original code, the class implemented a function getItemIndex(), which (i suppose) served to retrieve the index of an item in order to set the SelectedItem. This can be done with the following code:

ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()


If you want to compare the current selection, you can also use the SelectedItem:

((BindableObject)ddlCtrlFile.SelectedItem).IntValue == (int)PluginTypes.Generic_XML


I'm sorry the code doesn't look very clear, those IntelliSense comments kind of obfuscate it. However if you copy it into VisualStudio or another text editor with syntax highlighting, it will be much clearer.

using System;
using System.Collections;

namespace Xanthos.Common.Tools {

    public class BindableObject {

        public const string TEXT = "Text";
        public const string VALUE = "Value";

        private string m_strText = "";
        private int m_strValue = 0;

        public string Text { get { return m_strText; } }
        public string Value { get { return m_strValue.ToString(); } }
        public int IntValue { get { return m_strValue; } }

        public BindableObject(int intValue, string strText) {
            m_strValue = intValue;
            m_strText = strText;
        }
    }
    /// <summary>
    /// Defines a nicer format for EnumBinder texts.
    /// </summary>
    public enum StringPrint {
        /// <summary>No change to the enum text.</summary>
        None = 0x01,
        /// <summary>Replaces underscores with blanks in the enum text.</summary>
        Underscores = 0x02,
        /// <summary>Inserts a blank in front on uppercase letters in the enum text.</summary>
        CamelCase = 0x04
    }

    public class StringHelper {
        /// <summary>
        /// Inserts a blank in front of each uppercase letter preceded by a lowercase letter.
        /// </summary>
        /// <param name="str">Input string in "CamelCase".</param>
        /// <returns>Output string not in "Camel Case" anymore.</returns>
        public static string SplitCamelCase(string str) {
            return SplitCamelCase(str, ' ');
        }

        /// <summary>
        /// Inserts a separator in front of each uppercase letter preceded by a lowercase letter.
        /// </summary>
        /// <param name="str">Input string in "CamelCase".</param>
        /// <param name="sep">Separator character to insert ('_' for instance).</param>
        /// <returns>Output string not in "Camel_Case" anymore.</returns>
        public static string SplitCamelCase(string str, char sep) {
            if (str.Length < 1) return str;
            string ret = str[0].ToString();
            for (int i = 1; i < str.Length; i++) {
                if (char.IsUpper(str[i]) && char.IsLower(str[i - 1]))
                    ret += sep.ToString();
                ret += str[i].ToString();
            }
            return ret;
        }
    }

    public class EnumBinder {

        /// <summary>
        /// Binds a Windows Forms ListControl (drop down list) with an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        public static void DataBind(System.Windows.Forms.ListControl objListControl, Type objEnumType) {
            DataBind(objListControl, objEnumType, Enum.GetValues(objEnumType), StringPrint.None);
        }

        /// <summary>
        /// Binds a Windows Forms ListControl (drop down list) with an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        /// <param name="style">An Element of the Xanthos.Common.Tools.StringPrint defining the way how the Text value will look.</param>
        public static void DataBind(System.Windows.Forms.ListControl objListControl, Type objEnumType, StringPrint style) {
            DataBind(objListControl, objEnumType, Enum.GetValues(objEnumType), style);
        }

        /// <summary>
        /// Binds a Windows Forms ListControl (drop down list) with a subset of an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        /// <param name="objValues">Array containing the values to display.</param>
        public static void DataBind(System.Windows.Forms.ListControl objListControl, Type objEnumType, Array objValues) {
            DataBind(objListControl, objEnumType, objValues, StringPrint.None);
        }

        /// <summary>
        /// Binds a Windows Forms ListControl (drop down list) with a subset of an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        /// <param name="objValues">Array containing the values to display.</param>
        /// <param name="style">An Element of the Xanthos.Common.Tools.StringPrint defining the way how the Text value will look.</param>
        public static void DataBind(System.Windows.Forms.ListControl objListControl, Type objEnumType, Array objValues, StringPrint style) {
            ArrayList objBindObjects = new ArrayList();
            // loop through each value
            foreach (int nValue in objValues) {
                string str = Enum.GetName(objEnumType, nValue);
                if (Convert.ToBoolean(StringPrint.Underscores & style)) str = str.Replace('_', ' ');
                if (Convert.ToBoolean(StringPrint.CamelCase & style)) str = StringHelper.SplitCamelCase(str);
                // add the current enum details as a bindable object
                objBindObjects.Add(new BindableObject(nValue, str));
            }
            // bind up
            objListControl.DataSource = null;
            objListControl.DisplayMember = BindableObject.TEXT;
            objListControl.ValueMember = BindableObject.VALUE;
            objListControl.DataSource = objBindObjects;
        }
    }

    public class WebEnumBinder {
        // this cannot be in the same class as the System.Windows.Forms.ListControl DataBind,
        // since a webproject doesn't want to include a reference to System.Windows.

        /// <summary>
        /// Binds a WebControls ListControl (combo box) with an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        /// <param name="style">An Element of the Xanthos.Common.Tools.StringPrint defining the way how the Text value will look.</param>
        public static void DataBind(System.Web.UI.WebControls.ListControl objListControl, Type objEnumType) {
            DataBind(objListControl, objEnumType, Enum.GetValues(objEnumType), StringPrint.None);
        }

        /// <summary>
        /// Binds a WebControls ListControl (combo box) with an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        /// <param name="style">An Element of the Xanthos.Common.Tools.StringPrint defining the way how the Text value will look.</param>
        public static void DataBind(System.Web.UI.WebControls.ListControl objListControl, Type objEnumType, StringPrint style) {
            DataBind(objListControl, objEnumType, Enum.GetValues(objEnumType), style);
        }

        /// <summary>
        /// Binds a WebControls ListControl (combo box) with a subset of an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        /// <param name="objValues">Array containing the values to display.</param>
        public static void DataBind(System.Web.UI.WebControls.ListControl objListControl, Type objEnumType, Array objValues) {
            DataBind(objListControl, objEnumType, objValues, StringPrint.None);
        }

        /// <summary>
        /// Binds a WebControls ListControl (combo box) with a subset of an enumeration.
        /// Code example: EnumBinder.DataBind(ddlLogType, typeof(Xanthos.Common.LogEntryType));
        /// Caution! To set the selected value programmatically: ddlLogType.SelectedValue = ((int)LogEntryType.Information).ToString()
        /// </summary>
        /// <param name="objListControl">Your list control you want to fill the values.</param>
        /// <param name="objEnumType">Type of enumeration which is the source for the list control.</param>
        /// <param name="objValues">Array containing the values to display.</param>
        /// <param name="style">An Element of the Xanthos.Common.Tools.StringPrint defining the way how the Text value will look.</param>
        public static void DataBind(System.Web.UI.WebControls.ListControl objListControl, Type objEnumType, Array objValues, StringPrint style) {
            ArrayList objBindObjects = new ArrayList();
            // loop through each value
            foreach (int nValue in objValues) {
                string str = Enum.GetName(objEnumType, nValue);
                if (Convert.ToBoolean(StringPrint.Underscores & style)) str = str.Replace('_', ' ');
                if (Convert.ToBoolean(StringPrint.CamelCase & style)) str = StringHelper.SplitCamelCase(str);
                // add the current enum details as a bindable object
                objBindObjects.Add(new BindableObject(nValue, str));
            }
            // bind up
            objListControl.DataSource = null;
            objListControl.DataTextField = BindableObject.TEXT; // this line changes compared to System.Windows.Forms
            objListControl.DataValueField = BindableObject.VALUE; // this line changes compared to System.Windows.Forms
            objListControl.DataSource = objBindObjects;
            objListControl.DataBind(); // this line changes compared to System.Windows.Forms
        }
    }
}


Did you like this article? There are hundreds more.

Comments:
Anonymous
2011-01-26 09:02:24
none
Anonymous
2011-06-27 16:31:20
<a href="http://www.xlpharmacy.com/viagra/buy.php">Buy Viagra</a> and do well, that's what a virus appear in my computer yesterday...
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
bb
ASP.NET RadioButton GroupName when inside a Repeater on Sun 10th Jun 8am
I was thankful on finding this nugget of code, which makes the groupname work out when slamming in radiobuttons in an asp.net repeater. http://www.codeguru.com/csharp/csharp/cs _controls/custom/article.php/c12371/


     
Your Ad Here
 
Copyright Open Source Institute, 2006