Đức Long
Đức Long

Reputation: 87

can not set ValueMember to listBox in winforms

I can't set ValueMember to listBox

I have class Skill

class Skill
    {
        public string skillId { get; set; }
        public string name { get; set; }

        public Skill()
        {
        }

        public Skill(string skillId, string name)
        {
            this.skillId = skillId;
            this.name = name;
        }
    }

I add list Skill to List

            List<Skill> skills = new List<Skill>();
            skills.Add(new Skill("1", "Long"));
            skills.Add(new Skill("2", "Nhi"));

            foreach (var item in skills)
            {
                listBox1.Items.Add(item);
                listBox1.ValueMember = "skillId";
                listBox1.DisplayMember = "name";
            }

The DisplayMember is displayed to listBox, but ValueMember not set to listBox When I click selected an item in ListBox, and click button, I'm print

Console.WriteLine("value id listbox1:" + listBox1.SelectedValue);

but it display nothing

value id listbox1:

Upvotes: 1

Views: 92

Answers (1)

T.S.
T.S.

Reputation: 19404

The answer is - you need to use DataSourse property for this

listBox1.ValueMember = "skillId";
listBox1.DisplayMember = "name";
listBox1.DataSource = skills; // where skills  = List<Skill>

And make sure that DataSourse is set last. It has performance implications.

If you need to remove items, you can either use BindingList<Skill> or don't bind to a list but to an array generated from this list (LINQ) - skills.ToArray(). Then you can always remove item from the list in memory and then call listBox1.DataSource = skills.ToArray() again.

Upvotes: 1

Related Questions