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<开发者_JAVA百科;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.
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" />
I believe this will work:
List<Person> people = GetDataFromSomewhere();
DropDownList ddl = new DropDownList();
ddl.DataTextField = "Name";
ddl.DataValueField = "Id";
ddl.DataSource = people;
ddl.DataBind();
ddl.SelectedValue = (from p in people
where p.Selected == true
select p.Id).FirstOrDefault().ToString();
If the 'Selected' part is imperative you could also bind using the following:
List<Person> ps = new List<Person>();
DropDownList dl = new DropDownList();
dl.Items
.AddRange(ps
.Select(p => new ListItem() {
Text = p.Name
, Value = p.ID
, Selected = p.Selected }).ToArray());
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.
I would do something like this after binding to the list.
private void SetSelected(int id)
{
foreach (ListItem li in list.Items)
{
li.Selected = false;
if (li.Value == id.ToString())
{
li.Selected = true;
}
}
}
精彩评论