有人可以说明我的NameValueCollection会返回Length属性而不是Name和Value可能会让我看到我在这里做错了什么。我不能为下拉列表设置DataTextField或DataValueField,它只是给我一个长度。
public NameValueCollection GetDisplayForumGroups()
{
using (CMSEntities db = new CMSEntities())
{
var forums = (from x in db.Forums where x.ParentID == null select new { Name = x.Title, Value = x.ForumID });
NameValueCollection collection = new NameValueCollection();
foreach (var forum in forums)
{
collection.Add(forum.Name, forum.Value.ToString());
}
return collection;
}
}
public Dictionary<string, int> GetDisplayForumGroups()
{
using (CMSEntities db = new CMSEntities())
{
Dictionary<string, int> forums = (from x in db.Forums where x.ParentID == null select x).ToDictionary(x => x.Title, x => x.ForumID);
return forums;
}
}
答案 0 :(得分:1)
您无法直接绑定到NameValueCollection
,因为它不提供合适的枚举器。标准枚举器仅通过键枚举。
然后你不应该首先使用NameValueCollection
,你应该使用通用Dictionary
,除非你需要每个键有多个值(即便如此,还有更好的选择)大多数情况下)。甚至还有一种用于自动制作字典的Linq方法:
Dictionary<string, int> forums = (from x
in db.Forums
where x.ParentID == null
select x)
.ToDictionary(x => x.Title, x => x.ForumID);