Bidning a Systems.Collections.Generics.Dictionary to a dropdownlist

I

Ily

Hi

I have a collection of person objects that are added to a dictionary,
each items is added with a unque key. Each person object has a first
name property, and a last name property

My problem is I want to bind this to a dropdown list so that the
DataValueField is set to the ID of the Person, and that the
DataTextField displays the firstname of the person. The problem is I
can only set the DataValueField to either "Key" or "Value", but I want
my value to be "FirstName" When I do this I get an error saying:

Databinding "System.Collections.Generic.KeyValuePair does not contain a
aproperty with the name FirstName"

Am I doing something wrong? Can I actually achive what I am trying to
do?
 
M

Mikeon

Databinding "System.Collections.Generic.KeyValuePair does not contain a
aproperty with the name FirstName"

Am I doing something wrong? Can I actually achive what I am trying to
do?


Try binding to the Values property of your dictionary.
 
G

Gozirra

Easier than you think.

DropDownList.DataSource = Dictionary.Values;

This works for me. Here's my full sample code which is complete BS of
course but does work.

System.Collections.Generic.Dictionary<string, Person> dict
= new Dictionary<string, Person>();

dict.Add("Robert", new Person("Robert", "Turner"));
dict.Add("Fred", new Person("Fred", "Flinstone"));
dict.Add("Willma", new Person("Willma", "Flinstone"));
ddl1.DataSource = dict.Values; // ddl1 is the
dropdownlist. but I'm sure you figured that out.
ddl1.DataTextField = "FirstName";
ddl1.DataValueField = "LastName";
ddl1.DataBind();
 
G

Gozirra

After rereading your post I think I misunderstood. As I now understand
it, you want the Value to be the Key from the dictionary and the Text
to be the persons first name. As far as I know this cannot be done
using simple databinding. I would suggest that you add the id as part
of the person object as well, allowing you to bind to the Values
property of the dictionary or you will have to enumerate the items in
the dictionary and add each item yourself.

Neither solution is difficult and will give you what I think you want.

Hope you find this helpful.
 
I

Ily

Ah....

Thats much better!!

I think that placing the id as part of the person object is the way to
go!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top