Could someone shed some light on this my NameValueCollection returns the Length property instead of Name and Value could some show me what im doing wrong here. I can’t set the DataTextField or DataValueField for the dropdownlist it just gives me length.
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;
}
}
You can’t bind directly to a
NameValueCollectionsince it doesn’t provide a suitable enumerator. The standard enumerator enumerates through the keys only.Then again you shouldn’t be using a
NameValueCollectionfor this in the first place, you should use the genericDictionaryunless you need multiple values per key (and even then there are better alternatives for most cases). There’s even a Linq method for automagically making a dictionary: