資料查詢與展示:DataList
DataList控制項可用於建立模板化的列表資料,可以顯示諸如一行中有多列的內容,可以用任何重複結構中的資料。
使用DataList控制項顯示資料
1、添加DataList控制項(資料)——DataList任務——單擊編輯模板——在項目範本的ItemTempalte中添加Label控制項——在Lable任務中——單擊編輯DataBindings——在Lable DateBindings對話方塊中為Text綁定資料——首先選中欄位綁定——在欄位綁定下拉框中選擇需要的欄位——然後在選擇自訂綁定進行代碼錶達式修改對要顯示的外鍵欄位對象進行修改來顯示相應的屬性——單擊確定——單擊結束模板編輯——在分隔字元模板的SeparatorTemplate中添加分隔控制項——結束模板編輯
2、資料繫結
(1)資料來源控制項綁定
在 ObjectDataSource 任務——單擊配置資料來源——單擊下一步——在定義資料方法中選擇Select選項中的方法——單擊完成(2)手動綁定資料(在後置代碼中編寫Binder 方法,在首次載入頁面時調用方法) this.DataList1.DataSource = 調用商務邏輯層的資料存取方法();
this.DataList1.DataBind();
分頁的實現
1、預存程序分頁
SQL語句:Select Top pageSzie * from 表名 where 條件 and id not in (Select Top PageSize * (CurrentPageIndex-1) id from 表 where 條件 order by 排序條件) order by 排序條件
2、使用分頁類分頁
步驟:(1)編寫資料查詢方法(查詢所有的方法)指定PagedDataSource執行個體對象的資料來源(2)分別設定允許分頁、頁大小、當前頁的屬性(3)指定資料顯示控制項的資料來源為該執行個體對象,並綁定
樣本
using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;
using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using PracticeMyBookShopBLL;
public partial class datalistBook : System.Web.UI.Page
{
//分頁屬性
private int Pater {
get{ return (int)ViewState["Page"]; }
set{ ViewState["Page"] = value; } }
//首次載入
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
//首次載入時設定當前頁
ViewState["Page"] = 1;
//首次載入時調用方法
Databind(); } }
//分頁資料繫結
private void Databind() {
//建立分類
PagedDataSource pagedDataSource = new PagedDataSource();
//綁定資料
pagedDataSource.DataSource = BookManager.GetHotBook();
//設定是否自動分頁功能
pagedDataSource.AllowPaging = true;
//設定每頁記錄數
pagedDataSource.PageSize = 5;
//設定當前頁
pagedDataSource.CurrentPageIndex = Pater;
lblCurrentPage.Text = "第" + (pagedDataSource.CurrentPageIndex + 1).ToString() + "頁共" + pagedDataSource.PageCount.ToString() + "頁";
SetEnable(pagedDataSource);
this.DataList1.DataSource = pagedDataSource;
DataList1.DataBind(); }
//上一頁
protected void btnPrev_Click(object sender, EventArgs e) {
Pater--;
Databind(); }
//下一頁
protected void btnNext_Click(object sender, EventArgs e){
Pater++;
Databind(); }
//根據條件設定是按鈕否可用屬性
private void SetEnable(PagedDataSource pagedDataSource) {
btnPrev.Enabled = true;
btnNext.Enabled = true;
if (pagedDataSource.IsFirstPage) {
btnPrev.Enabled = false; }
if (pagedDataSource.IsLastPage) {
btnNext.Enabled = false;
} } }
分頁類的屬性 |
屬性 |
說明 |
CurrentPageIndex |
當前頁 |
PageCount |
總頁數 |
Count |
總記錄數 |
PageSize |
每頁記錄數 |
DataSource |
資料來源 |
AllowPaging |
控制項是否實現自動分頁功能 |