首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

DropDownList 數據綁定三大實戰技巧:Enum、List<T>、首項為空

     編輯:關於ASP.NET

技巧一:Enum 一鍵綁定

// 僅名稱
DropDownList1.DataSource = Enum.GetNames(typeof(OrderStatus));
DropDownList1.DataBind();

// 需要值:轉換為鍵值對
var items = Enum.GetValues(typeof(OrderStatus))
    .Cast()
    .Select(e => new ListItem(e.ToString(), ((int)e).ToString()));
DropDownList1.DataSource = items;
DropDownList1.DataBind();

技巧二:List<T> 對象集合綁定

var logistics = new LogisticsBLL().GetAll(); // List
DropDownList3.DataSource = logistics;
DropDownList3.DataTextField = "Name";   // 顯示字段
DropDownList3.DataValueField = "Id";    // 值字段(通常為主鍵)
DropDownList3.DataBind();

關鍵:DataTextField/DataValueField 必須匹配對象屬性名(區分大小寫)。

技巧三:首項插入「請選擇」空項

❌ 錯誤做法:覆蓋首項數據

DropDownList3.DataBind();
DropDownList3.Items[0].Text = "";  // 丟失原第一條數據!

✅ 正確做法:插入新項保留原數據

DropDownList3.DataSource = logistics;
DropDownList3.DataTextField = "Name";
DropDownList3.DataValueField = "Id";
DropDownList3.DataBind();
DropDownList3.Items.Insert(0, new ListItem("請選擇", "")); // 索引 0 插入

進階:綁定後統一設置默認選中

DropDownList3.DataBind();
DropDownList3.Items.Insert(0, new ListItem("請選擇", ""));
// 根據業務邏輯設置
if (defaultLogisticsId > 0) 
    DropDownList3.SelectedValue = defaultLogisticsId.ToString();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved