[英]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
List<RequestStatus> nextStatus = new List<RequestStatus>();
nextStatus.Add(RequestStatus.Review);
nextStatus.Add(RequestStatus.InProgress);
If we want to bind nextStatus
to dropDownList
we do it as belllow 如果我们想将
nextStatus
绑定到dropDownList
我们将其作为波纹管
foreach (RequestStatus 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): 绑定是在设置数据源和绑定,而不是在列表中添加项目,而您正在寻找的是(假设这里是ASP.NET Forms):
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. 话虽这么说,我认为这对用户的友好程度很差,因为我当然不会在下拉列表中看到“ InProgress”。 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:
我认为将ID / Name / Key和DisplayName组合存储在某个位置,然后像下面这样绑定ID和DisplayName会更合适:
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. 为了澄清起见,我不主张对该列表进行硬编码,并且可能会从数据库和缓存中加载该列表,但是我真的只能在这里猜测您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.