Reputation: 8695
I want to have an Enum that's built from a database query and I'm stuck at how to do it. My thought was to have a method that returns a list of strings and use that to fill the Enum, but I'm unsure if that's possible or the proper way to do it. The table that the Enum will be built from will change very infrequently. What's a good way to get at this?
enum DrugColor
{
}
private List<string> BuildEnum()
{
List<string> EnumList = new List<string>();
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("select color from DrugColors", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string colorName;
colorName = rdr["Color"].ToString();
EnumList.Add(colorName);
}
}
return EnumList;
}
}
Upvotes: 0
Views: 11669
Reputation: 351
Enums are created at design time. In short, you would not be generating an enum during run time instances, so you're describing a need for code-writing code. How many distinct drug colors are there? Seems like this is done just as easily by hand.
Upvotes: 1
Reputation: 1492
So your function should return a list of enums:
private List<DrugColor> BuildEnum()
Thats the first thing. When you declar the list you return, change it to a list of enum too:
List<DrugColor> EnumList = new List<DrugColor>();
When you take the data from the database, each read() is a color so color name is a DrugColor
DrugColor colorName;
colorName = new DrugColor{(DrugColor)Enum.Parse(typeof(DrugColor ),rdr["Color"].ToString()); }
With this you parse the string into the enum.
And then you add it to the list
Voila!
EDIT:
Your enum should contain things:
enum DrugColor
{
Red,
Blue,
Yellow
}
Upvotes: 2