Mettre des objets dans une DropDownList
Bonsoir
Je cherche à mettre des objets "Personne" dans une DropDownList afin de pouvoir récupérer l'objet séléctionné lors du clic sur un bouton.
Plus concrètement :
La classe Personne contient deux attributs : id de type int et name de type string.
Code:
1 2 3 4 5
| <p>
<asp:DropDownList ID="DropDownList" runat="server"></asp:DropDownList>
<asp:Button ID="Button" runat="server" Text="Valider" onclick="Button_Click" />
<asp:Literal ID="Literal" runat="server"></asp:Literal>
</p> |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| protected void Page_Load(object sender, EventArgs e)
{
List<Person> persons=new List<Person>();
persons.Add(new Person(21,"Nom 1"));
persons.Add(new Person(34,"Nom 2"));
DropDownList.DataSource = persons;
DropDownList.DataTextField = "name";
DropDownList.DataBind();
}
protected void Button_Click(object sender, EventArgs e)
{
Literal.Text = Request.Form["DropDownList"];
} |
La quand je clique sur Valider, ca inscrit l'attribut name de l'objet séléctionné dans le literal "Literal". Comment pourrai-je, au clic sur le bouton, récupérer l'attribut id de l'objet séléctionné en affichant les noms dans la DropDownList ?