好吧,如果您在 ListView 中有 DropDownList,那么我将使用以下方法(它可能可以优化,我的 ASP.NET Web 窗体技能正在生锈)。
模型:
public enum AnimalType
{
Dog = 1,
Cat = 2,
Sheep = 3,
Horse = 4
}
public class Animal
{
public string Name { get; set; }
public AnimalType Type { get; set; }
}
页:
<asp:ListView ID="lstAnimals" runat="server" onitemdatabound="lstAnimals_ItemDataBound">
<ItemTemplate>
<div>
<asp:TextBox runat="server" Text='<%#Eval("Name") %>' />
<asp:DropDownList ID="lstAnimalType" runat="server" DataValueField="Id" DataTextField="Description" />
</div>
</ItemTemplate>
代码背后:
protected void Page_Load(object sender, EventArgs e)
{
var animals = new List<Animal>();
animals.Add(new Animal() { Name = "Doggie", Type = AnimalType.Dog});
animals.Add(new Animal() { Name = "Sheepie", Type = AnimalType.Sheep });
lstAnimals.DataSource = animals;
lstAnimals.DataBind();
}
protected void lstAnimals_ItemDataBound(object sender, ListViewItemEventArgs e)
{
var ddlAnimalType = (DropDownList)e.Item.FindControl("lstAnimalType");
var enumValues = Enum.GetValues(typeof (AnimalType)).Cast<AnimalType>().ToList();
var bindableList = enumValues.Select(v => new { Id = (int) v, Description = v.ToString() });
ddlAnimalType.DataSource = bindableList;
ddlAnimalType.DataBind();
}