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

ASP.NET 資料繫結控件基礎入門 (一):DropDownList、ListBox、GridView、DataList 核心屬性與用法

     編輯:關於ASP.NET

資料繫結控件基礎架構

所有資料繫結控件繼承 `BaseDataBoundControl`,核心成員:

  • DataSource:物件參考,指定資料來源 (實作 `IEnumerable`/`IListSource`/`ICollection`)。
  • DataSourceID:字串,指定資料來源控件 ID (如 `SqlDataSource`、`ObjectDataSource`)。優先級高於 DataSource。
  • DataBind():方法,執行繫結動作。設定來源後必須呼叫才會顯示資料。

下拉式清單控件

DropDownList - 單選下拉選單

轉譯為 ``,`SelectionMode`:`Single` (預設) / `Multiple`。屬性同 DropDownList,另具 `GetSelectedIndices()` 取得多選索引陣列。

表格式資料控件

GridView - 功能最完整的表格控件

支援分頁 (`AllowPaging`)、排序 (`AllowSorting`)、編輯/刪除 (`AutoGenerateEditButton`/`DeleteButton` 或 `CommandField`)、資料鍵 (`DataKeyNames`)、空資料模板 (`EmptyDataTemplate`)。欄位類型:`BoundField`、`TemplateField`、`CheckBoxField`、`HyperLinkField`、`ButtonField`、`ImageField`、`CommandField`。

DataList - 可重複方向的流式版面

`RepeatDirection`:`Vertical`/`Horizontal`;`RepeatColumns` 控制水平重複數;`RepeatLayout`:`Table` (預設) / `Flow` (無表格,用 span/div)。模板:`ItemTemplate`、`AlternatingItemTemplate`、`SelectedItemTemplate`、`EditItemTemplate`、`HeaderTemplate`、`FooterTemplate`、`SeparatorTemplate`。

基本繫結範例:DropDownList 繫結列舉

public enum OrderStatus { Pending = 1, Processing = 2, Shipped = 3, Completed = 4 }

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlStatus.DataSource = Enum.GetValues(typeof(OrderStatus));
        ddlStatus.DataBind(); // Text/Value 均為列舉名稱/數值
    }
}

繫結資料表到 GridView

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string sql = "SELECT UserId, UserName, RealName, Age FROM Users";
        DataTable dt = DbHelper.GetDataTable(sql);
        gvUsers.DataSource = dt;
        gvUsers.DataBind();
    }
}

常見問題與解決

  • 重複繫結導致資料疊加:確保 `!IsPostBack` 內繫結,或繫結前 `Control.Items.Clear()` (列表控件)。
  • SelectedValue 設定失效**:資料繫結完成後才設定 `SelectedValue`,或資料來源不包含該值。
  • GridView 分頁/排序不生效**:需設定 `AllowPaging`/`AllowSorting` 並處理 `PageIndexChanging`/`Sorting` 事件重新繫結。

總結

掌握 `DataSource`/`DataSourceID`/`DataBind()` 三要素與各控件關鍵屬性,是駕馭 ASP.NET 資料繫結的基礎。DropDownList/ListBox 適合選單輸入;GridView 適合完整表格管理;DataList 適合自訂版面流式呈現。選對控件,事半功倍。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved