Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulating dropdown list with enum using reflection
    text
    copied!<p>I am populating a page with controls reading properties of a class using reflection. If the property type is <code>'String'</code> I will add a text-box. If the property type is enum I am adding a dropdownlist. Now I have to populate the dropdown options with enums. How can this be done?</p> <p>Both the enum definition class(<code>Assignment</code>) and the class(<code>classOne</code>) using which I am populating the page with controls are in the same <code>Namespace(MySolution.Data)</code>. While looping through classOne properties when the property name is 'SkillLevel' I will have to go to assignment class get the members of enum <code>SkillLevelEnum</code> and populate the dropdown.</p> <p>Same needs to be done for other dropdowns also.</p> <p><strong>My Code:</strong></p> <pre><code>namespace MySolution.Data { public class classOne : MyAdapter { private string _Model; public string Model { get { return _Model; } set { _Model = value; } } private Assignement.SkillLevelEnum _SkillLevel; public Assignement.SkillLevelEnum SkillLevel { get { return _SkillLevel; } set { _SkillLevel = value; } } private Assignement.MinimalSkillsEnum _MinimalSkill; public Assignement.MinimalSkillsEnum MinimalSkill { get { return _MinimalSkill; } set { _MinimalSkill = value; } } public Assignemen.WorkLoadEnum WorkLoad { get { return _WorkLoad; } set { _WorkLoad = value; } } } public class Assignement : MyAdapter { #region Enumerations public enum SkillLevelEnum { LowerSkills = 0, HighestSkills = 1, Any = 2 } public enum MinimalSkillsEnum { Accountable = 0, Responsible = 1, Expert = 2, Senior = 3, Medium = 4, Junior = 5 } public enum WorkLoadEnum { LessBusy = 0, MostBusy = 1, Any = 2 } #endregion } } </code></pre> <p>Thanks</p> <p><strong>Edit:</strong></p> <p>I don't want to hardcode any of the property names. I am looping through the properties as below.</p> <p>properties = Utility.GetAllPropertyForClass("className")</p> <p>Panel panel = new Panel();<br> panelMe.Controls.Add(panel);</p> <p>foreach (PropertyInfo property in properties) {</p> <pre><code> if (!property.PropertyType.IsEnum) { TextBox txt = new TextBox(); txt.ID = "txt" + i.ToString(); panel.Controls.Add(txt); } else { DropDownList ddl = new DropDownList(); ddl.ID = "ddl" + i.ToString(); // Here based on the property.name i need to get the enum members which is defined in a different class using reflection panel.Controls.Add(ddl); } panel.Controls.Add(new LiteralControl("&lt;br/&gt;")); i++; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload