I have a class with constant strings in it. I'd like to throw all of those strings into a drop down collection. What is the best way to do this? This is what I have now and in theory, I would think that it would be the best way to do this.
public class TestClass
{
private const string _testA = "Test A";
private const string _testB = "Test B";
public string TestA
{
get { return _testA; }
}
public string TestB
{
get { return _testB; }
}
}
public DropDownItemCollection TestCollection
{
DropDownItemCollection collection = new DropDownItemCollection();
TestClass class = new TestClass();
foreach (string testString in class)
{
DropDownItem item = new DropDownItem();
item.Description = testString;
item.Value = testString;
collection.Add(item);
}
return collection;
}
The problem is that this returns an error on the foreach: "...does not contain a public definition for GetEnumerator." I've tried to create a GetEnumerator but I've been unsuccessful and I haven't worked with GetEnumerator in the past.
Any help is greatly appreciated!
I just had the same challenge; to get all constants of my class (not properties!). Based on the most popular answer (for properties) and John's answer (for constants) I wrote this. I tested it and it works well.
You can use reflection to loop trought the class properties:
A little late but wouldn't this be a better solution?
http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx
If you need the names you can do
inside the loop.
You could implement a method that yields the strings:
Else you should look into reflection to return the properties that are static and string and then get the values by calling them.
Regards GJ
You could use reflection to loop through all the properties:
You need to use reflection to get name of each String from your custom type, and then also/optionally get the value of each one of those Strings...
Something like this: