List<MyClass> as datasource for DropDownList?

12,687

For web based ASP.net

You need to specify the drop down lists datatextfield and datavaluefield properties.

MyDropDownList.DataSource = myList;
MyDropDownList.DataTextField="Name";
MyDropDownList.DataValueField="ID"; 
MyDropDownList.DataBind();

For win form

You need to specify the displaymember / valuemember properties.

Just noticed this is a winform application try this:

MyDropDownList.DataSource = myList;
MyDropDownList.DisplayMember = "Name";
MyDropDownList.ValueMember = "ID";
Share:
12,687
Prix
Author by

Prix

Looking forward to learn more and more :)

Updated on June 08, 2022

Comments

  • Prix
    Prix almost 2 years

    I have a simple Class with ID and Name on it which I would like to link to a DropDownList but it seems that myDropDownList.DataTextField = "Name"; and myDropDownList.DataValueField = "ID"; are not accessible or available.

    UPDATE: I am using winforms

    public class Test
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    
    List<Test> myList = new List<Test>()
    {
        // bla bla bla some entries bla bla bla you got the point.
    };
    myDropDownList.DataSource = myList;
    

    I know I could override ToString but that would not help me with the value of each entry on the list.

    Are there any other options to print the Name on the dropdownlist while having another property as the value (ie: printing Name while having the selected value or item as the ID) ?

  • LoganS
    LoganS almost 13 years
    @Prix no problem, I'm glad you solved it. And no it wasn't a silly question, it was quite valid and something that other developers may forget :) or beginners may never know.
  • Prix
    Prix almost 13 years
    eheheh true, well I know I could use it but was setting it at the wrong place for the dropdownlist.