Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I DataBind a List<> of objects to a DropDownList and set the SelectedItem based on a property in the object?

How can I DataBind a List<> of objects to a DropDownList and set the SelectedItem based on a property in the object?

For example, say I have a List<Person>

Where Person has 3 properties...

Person .Name (string)
       .Id  (int)
       .Selected (bool)

I want the first one with Selected == true to be the SelectedItem in the list.

like image 488
user135799 Avatar asked May 05 '11 21:05

user135799


People also ask

Which property on a DropDownList do you set with a column name before setting the DataSource to show data in the DropDownList?

Local Data Specify the column names in the Fields property.

How do I add a default item to DropDownList?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.


2 Answers

I had the same question just now but I figured out that writing the code to manually add the items from my List was shorter or as long as than other solutions described.

Thus something like this should work for you:

        //bind persons
        foreach(Person p in personList)
        {
            ListItem item = new ListItem(p.Name, p.Id.ToString());
            item.Selected = p.Selected;
            DropDownListPerson.Items.Add(item);
        }

Just make sure to check the IsPostBack as well as checking whether the list already has items or not.

like image 108
Rowan Jugernauth Avatar answered Sep 21 '22 21:09

Rowan Jugernauth


Try this:

List<Person> list = new List<Person>();
// populate the list somehow

if ( !IsPostBack )
{
    DropDownList ddl = new DropDownList();
    ddl.DataTextField = "Name";
    ddl.DataValueField = "Id";
    ddl.DataSource = list;
    ddl.DataBind();

    ddl.SelectedValue = list.Find( o => o.Selected == true ).Id.ToString();
}

If you can't guarantee that there will always be at least one selected item, then you'll want to handle that separately by checking the return value from the list.Find() call to make sure it is not null.

Also, DropDownList ddl = new DropDownList(); not needed if the webform has already declared:

<asp:DropDownList ID="ddl" runat="server" />
like image 29
Katie Kilian Avatar answered Sep 22 '22 21:09

Katie Kilian