First of all here is our markup code in our .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Sandbox.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList> </div> </form> </body> </html>
Now let's define our enum type, the last value is 400 just to confirm that the DropDownList1 control is taking the value of the enum type as the value field
public enum CategoryEnum { Beverages = 1, Condiments = 2, Confections = 3, DairyProducts = 400 }
Once we have our enum type define we can iterate through our enum type with a foreach loop and add a new ListItem object to the DropDownList control. Like the code below.
foreach(int cat in Enum.GetValues(typeof(CategoryEnum))) { DropDownList1.Items.Add(new ListItem(Enum.GetName(typeof(CategoryEnum),cat), cat.ToString())); }
One of the ListItem method signature is ListItem(string text, string value), we use the Enum.GetName(Type enumType, Object value) to get the string name of the enum. Then we pass in the current value of the enum with the current int value cat in foreach loop and convert into a string to satisfy the ListItem method signature.
When you run the page you will see that the DropDownList1 control is now populated with the CategoryEnum values
If you look at the generated html markup for the DropDownList1 control you will see that both the value and the text value has been set correctly.
<div> <select name="DropDownList1" id="DropDownList1"> <option value="1">Beverages</option> <option value="2">Condiments</option> <option value="3">Confections</option> <option value="400">DairyProducts</option> </select> </div>
Mua vé máy bay tại Aivivu, tham khảo
ReplyDeletesăn vé máy bay giá rẻ đi Mỹ
vé máy bay mỹ về việt nam
cách mua vé máy bay từ nhật về việt nam
các chuyến bay từ đức về việt nam hôm nay
vé máy bay từ canada về việt nam bao nhiêu tiền
khi nào mở lại đường bay hàn quốc
ve may bay cho chuyen gia nuoc ngoai