views:

75

answers:

1

Hi,

I've seen lots of posts about binding a dictionary to a drop down when the value is a string.

What if the value is a class with a particular property of that class being the one thats displayed in the drop down?

Dictionaty

// Value class MyClass { public String Yer="123"; public String Ner="321"; }

How do I display property Yer in my dropdown that's bound to that dictionary?

A: 

You need to use the DataTextField and DataValueField properties to the combo. Try this:

    private void Page_Load(object sender, EventArgs e)
    {
        List<MyDummyObject> data = new List<MyDummyObject>() 
            { 
                 new MyDummyObject() {ID = 1, RandomBoolValue = true, SomeRandomDescription = "First item" } 
                ,new MyDummyObject() {ID=2, RandomBoolValue = false, SomeRandomDescription = "Second item" }
            };

        comboBox1.DataTextField = "SomeRandomDescription";
        comboBox1.DataValueField = "ID";
        comboBox1.DataSource = data;
        comboBox1.DataBind();
    }


    private class MyDummyObject
    {
        public int ID { get; set; }
        public string SomeRandomDescription { get; set; }
        public bool RandomBoolValue { get; set; }

        public override string ToString()
        {
            return "zzzzzz";
        }
    }

The overridden ToString on MyDummyObject is just to prove that it isn't being called (which is the default action if you don't specify DataTextField or DataValueField).

slugster
These properties do not exist on the ASP.NET DropDownList unfortunatly
Sir Psycho
Ahh sorry, i'm sure you originally had Winforms in your comment above? Never mind, i have amended my answer.
slugster