`DropDownList` 是 ASP.NET WebForms 中常用的下拉列表控制項,本質是 `ListItem` 集合的容器。每個 `ListItem` 包含 `Text`(顯示文字)與 `Value`(提交值)兩屬性。根據數據來源不同,綁定方式主要分為三類。
直接在 `.aspx` 標記中聲明,適合極少變動的選項(如城市、狀態碼)。
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">南京</asp:ListItem>
<asp:ListItem Value="2">揚州</asp:ListItem>
<asp:ListItem Value="3">徐州</asp:ListItem>
<asp:ListItem Value="4">蘇州</asp:ListItem>
</asp:DropDownList>
優點:直觀、無後台代碼、效能最高。
缺點:修改需改代碼、無法動態響應數據庫變更。
從資料庫查詢 `DataTable`/`DataView`/`List<T>` 等數據源,設定 `DataTextField`、`DataValueField` 後呼叫 `DataBind()`。
// 假設已從資料庫獲取 DataTable dt,包含 CityId、CityName 兩欄
DataTable dt = GetCityDataFromDatabase(); // 自行實現查詢邏輯
DropDownList1.DataSource = dt.DefaultView;
DropDownList1.DataTextField = "CityName"; // 顯示欄位
DropDownList1.DataValueField = "CityId"; // 提交值欄位
DropDownList1.DataBind(); // 執行綁定
// 可選:插入預設提示項
DropDownList1.Items.Insert(0, new ListItem("-- 請選擇城市 --", ""));
適用場景:選項來自資料庫、需隨權限/條件動態變化、多頁面共用相同選項(可封裝為通用方法)。
不依賴數據源,直接操作 `Items` 集合,適合邏輯生成、條件添加、少量動態項目。
ListItem li = new ListItem();
li.Text = "南京";
li.Value = "1";
DropDownList1.Items.Add(li);
// ListItem(Text, Value)
DropDownList1.Items.Add(new ListItem("揚州", "2"));
string[] cities = { "南京", "揚州", "徐州", "蘇州" };
for (int i = 0; i < cities.Length; i++)
{
DropDownList1.Items.Insert(i, new ListItem(cities[i], i.ToString()));
// 或使用 Add,Insert 可指定索引位置
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // 關鍵:僅首次載入綁定
{
BindDropDownList();
}
}
///
/// 通用下拉綁定方法
///
public static void BindDropDownList(DropDownList ddl, object dataSource,
string textField, string valueField, string defaultText = "-- 請選擇 --")
{
ddl.DataSource = dataSource;
ddl.DataTextField = textField;
ddl.DataValueField = valueField;
ddl.DataBind();
if (!string.IsNullOrEmpty(defaultText))
ddl.Items.Insert(0, new ListItem(defaultText, ""));
}
// 設定選中值(按 Value)
DropDownList1.SelectedValue = "2"; // 選中「揚州」
| 方式 | 適用場景 | 維護性 | 效能 | 靈活度 |
|---|---|---|---|---|
| 前台靜態聲明 | 極少變動、極簡選項 | 低 (改代碼重編譯) | 最高 | 低 |
| 後台動態綁定數據源 | 資料庫驅動、多頁共用、權限控制 | 高 (集中管理) | 高 | 高 |
| 後台手動添加 ListItem | 邏輯生成、條件組合、少量動態項 | 中 | 高 | 最高 |
掌握三種綁定方式並能根據業務場景靈活選擇,是 ASP.NET WebForms 開發的基本功。