开发者

What's Best way to Bind collection of Enums ( List<Enum> ) to a DropDownList?

If I have the following enum

enum RequestStatus
    {
        Open = 1,
        InProgress = 4,
        Review = 7,
        Accepted = 11,
        Rejected = 12,
        Closed = 23
    }

and we have the following List

List<RequestStatus> nextStatus = new List<RequestStatus>();
nextStatus.Add(RequestStatus.Review);
nextStatus.Add(RequestStatus.InProgress);

If we want to bind nextStatus to dropDownListwe do it as belllow

foreach (Reque开发者_开发技巧stStatus req in nextStatus)
    dropDownList.Items.Add(new ListItem(req.ToString(), ((int)req).ToString()));

Is there any other best way to do this bind ?


Binding is setting a data source and bindings, not adding items to a list, what you are looking for is (assuming this is ASP.NET Forms here):

dropdownlist.DataSource = Enum.GetNames(typeof(RequestStatus))
dropdownlist.DataBind();

That being said, I think this is pretty poor user friendliness as I certainly would not care to see "InProgress" in a dropdown. I think it would be more appropriate to store this data with a ID/Name/Key and DisplayName combo somewhere and then bind the ID and DisplayName like so:

var items = new[] {{ID = "Review", DisplayName = "Review"}, {ID = "InProgress", DisplayName="In Progress"}};
dropdownlist.DataSource = items;
dropdownlist.DataValueField = "ID";
dropdownlist.DataTextField = "DislayName";
dropdownlist.DataBind();

To clarify I am not advocating to hardcode this list and would probably load this from DB and cache, but I really can only guess at your requirements here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜