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.
Local Data Specify the column names in the Fields property.
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.
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.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With