如何把Databean List邦定到Grid
問題:
習慣用Java編寫3層架構程式的人都會提出這樣的疑問:能否把現行的Java架構移植到dotNet中來。回答是肯定的。
在移植過程中我們首先要遇到的問題是,在Java中我們Databean來傳遞資料,而dotNet中調用Ado.NET傳回值是DataTable或DataSet,並且Grid控制項的DataSource資料也能直接接收DataTable或DataSet對象。所以目前很多人都用 DataTable或DataSet對象作為資料轉送對象。
用 DataTable或DataSet對象作為資料轉送對象有一個缺點,當我們要對DataTable或DataSet對象內的資料作處理時要用行號和列名去取得值,導致資料訪問層和商務邏輯層,展示層聯絡緊密,無法做到徹底分離,邏輯混亂。
解決方案:
首先在資料訪問層把DataTable或DataSet對象轉換成Databean的List,然後再用Databean的List直接邦定到Grid控制項上。
例子:
把DataTable或DataSet對象轉換成Databean的List的例子等到架構做好後再公布。現在先給出用Databean的List直接邦定到Grid控制項上的例子。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>無題のページ</title> </head> <body> <form id="form1" runat="server"> <asp:DataGrid id="DataGrid1" runat="server" Width="529px" Height="208px" AutoGenerateColumns="False"> <Columns> <asp:BoundColumn HeaderText="a1" DataField="product_id"></asp:BoundColumn> <asp:BoundColumn HeaderText="a2" DataField="product_nm"></asp:BoundColumn> </Columns> </asp:DataGrid> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList> </form> </body> </html> |
using System; using System.Data; using System.Configuration; 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 System.Collections; using System.Collections.Generic; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 在此處放置使用者代碼以初始化頁面 Test t = new Test(); t.LoadData(); this.DataGrid1.DataSource = t.RowCollection; this.DataGrid1.DataBind(); this.DropDownList1.DataTextField = "Product_nm"; this.DropDownList1.DataValueField = "Product_id"; this.DropDownList1.DataSource = t.RowCollection; this.DropDownList1.DataBind(); } } public class RowData { private string product_id; private string product_nm; public string Product_id { get { return product_id; } set { product_id = value; } } public string Product_nm { get { return product_nm; } set { product_nm = value; } } public RowData(string id, string des) { this.Product_id = id; this.Product_nm = des; } } class Test { private List<RowData> m_RowDataCollection; public List<RowData> RowCollection { set { m_RowDataCollection = value; } get { return m_RowDataCollection; } } public void LoadData() { this.RowCollection = new List<RowData>(); this.RowCollection.Add(new RowData("7201", "aaaaaa")); this.RowCollection.Add(new RowData("7202", "aaaaaa")); this.RowCollection.Add(new RowData("7203", "aaaaaa")); this.RowCollection.Add(new RowData("7204", "aaaaaa")); } } |