只要是有使用 ASP.NET 的人都知道 DropDownList 是下拉選項的元件, 但是要如何做才能即簡單又好維護呢?
我的建議是使用 enum, 因為用 enum 可以即清楚又明白的設置下拉內容, 日後也好維護, 力挺啦!
//aspx 檔中的程式
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="morseTestWebApp.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center;">
<asp:DropDownList ID="ddlEnumTest" runat="server" OnSelectedIndexChanged="ddlEnumTest_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</div>
</form>
</body>
</html>
//cs 檔中的程式
using System;
using System.Diagnostics;
using System.Web.UI.WebControls;
namespace morseTestWebApp
{
// 宣告一組的 enum
[Flags]
public enum DayHaveValue
{
Sunday = 10,
Monday = 20,
Tuesday = 30,
Wednesday = 40,
Thursday = 50,
Friday = 60,
Saturday = 70
};
public partial class WebForm1 :System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
// 為 DropDown 元件填入資料
foreach(var s in Enum.GetValues(typeof(DayHaveValue))) {
ddlEnumTest.Items.Add(new ListItem(s.ToString(), ((int)s).ToString()));
}
}
protected void ddlEnumTest_SelectedIndexChanged(object sender, EventArgs e) {
// 檢視選擇改變後的數據,返回的是 Value 而不是 Text
Debug.WriteLine(ddlEnumTest.SelectedValue);
}
}
}
留言列表