也會用一些如eval,bind,container.dataitem等,也正如我們所知
Eval 單向綁定:數(shù)據(jù)是只讀的,<%# Eval("字段名") %>,能從數(shù)據(jù)庫讀出相應數(shù)據(jù),不能寫入,更改。
Bind 雙向綁定:數(shù)據(jù)可以更改,數(shù)據(jù)可以更改,并返回服務器端,服務器可以處理更改后的數(shù)據(jù),如存入數(shù)據(jù)庫
這里我們重點起來看看container.dataitem的用法,
假如
后臺:
this.GridView.DataSource=new String[]{"AA","BB","CC"};
this.GridView.DataBind();
前臺:不知道怎么綁定才能顯示初數(shù)組的值?
這個問題其實很簡單,前臺只需要<%#Container.DataItem%>即可,可能最主要問題是大家對這里Container.DataItem不是很理解,
下面對常用的一些顯示方法做一簡單解釋:
綁定到簡單屬性:<%#UserName%>
綁定到集合:<asp:ListBox id="ListBox1" datasource='<%# myArray%>' runat="server">
綁定到表達式:<%#(class1.property1.ToString() + "," + class1.property2.ToString())%>
綁定到方法返回值:<%# GetSafestring(str) %>
綁定到Hashtable:<%# ((DictionaryEntry)Container.DataItem).Key%>
綁定到ArrayList:<%#Container.DataItem %>
若數(shù)組里里放的是對象則可能要進行必要的轉(zhuǎn)換后再綁定如:
<%#((對象類型)Container.DataItem).屬性%>
綁定到DataView,DataTable,DataSet:
<%#((DataRowView)Container.DataItem)["字段名"]%>或
<%#((DataRowView)Container.DataItem).Rows[0]["字段名"]%>
要格式化則:
<%#string.Format("格式",((DataRowView)Container.DataItem)["字段名"])%>
<%#DataBinder.eval(Container.DataItem,"字段名","格式")%>
若GridView中綁定列里面設(shè)置了內(nèi)容格式 DataFormateString ,則必須把 屬性 HtmlCode 設(shè)置為false,否則無法起作用
綁定到DataReader:
<%#((IDataReader)Container.DataItem).字段名%>
當然為了方便一般使用最多的就是DataBinder類的Eval方法了.不過這樣對于同時要綁定大量的數(shù)據(jù)效率要低一些
在綁定數(shù)據(jù)時經(jīng)常會用到這個句程序:<%# DataBinder.eval(Container.DataItem,"xxxx")%>或者<%# DataBinder.eval(Container,"DataItem.xxxx")%>
今天又學到一種,而且微軟也說這種方法的效率要比以上兩種高。
<%# ((DataRowView)Container.DataItem)["xxxx"]%>
很有用的,這樣可以在前臺頁面做好多事情了。
還要記住要這樣用必須要在前臺頁面導入名稱空間System.Data,否則會生成錯誤信息。
<%@ Import namespace="System.Data" %>
這種用法其實和<%# ((DictionaryEntry)Container.DataItem).Key%>是一個道理。
綁定到DataSet、DataTable時:
<%#((System.Data.DataRowView)Container.DataItem)["字段名"]%>
<%#((System.Data.DataRowView)Container.DataItem)[索引]%>
綁定到DataReader時:
<%#((System.Data.Common.DbDataRecord)Container.DataItem)[索引]%>
<%#((System.Data.Common.DbDataRecord)Container.DataItem)["字段名"]%>
關(guān)鍵是Container這個東西,它比較神秘。它的名稱空間是System.ComponentModel。對于它我還需要進一步理解。
初學.NET,現(xiàn)在在看DataGrid控件,在ItemTemplate顯示數(shù)據(jù)時,
DataBinder.eval(Container.DataItem,"Name")和Container.DataItem("Name")有什么區(qū)別?
DataBinder是System.Web里面的一個靜態(tài)類