List作為GridView資料來源時,繫結模板列的例子

鴨脖發表於2013-12-03

List<string> attributes = new List<string>();
【轉載】List作為GridView資料來源時,繫結模板列的例子
narf.DataSource 
= attributes;
narf.DataBind();


.aspx

<asp:gridview ID="narf" runat="server">
 
<Columns>
 
<asp:TemplateField>
 
<ItemTemplate>
 
<asp:TextBox ID="nasdc" runat="server" Text=<%# Container.DataItem %>></asp:TextBox>
 
</ItemTemplate>
 
</asp:TemplateField>
 
</Columns>
</asp:gridview>




http://www.cnblogs.com/stu-acer/archive/2009/03/23/1419582.html



http://forums.asp.net/t/1050997.aspx





靈活的運用資料繫結操作
 
繫結到簡單屬性:<%#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 %>


 
若陣列裡裡放的是物件則可能要進行必要的轉換後再繫結如:
 
<%#((物件型別)Container.DataItem).屬性%>


 
繫結到DataView,DataTable,DataSet:
 
<%#((DataRowView)Container.DataItem)["欄位名"]%>或
 
<%#((DataRowView)Container.DataItem).Rows[0]["欄位名"]%>
 
要格式化則:
 
<%#string.Format("格式",((DataRowView)Container.DataItem)["欄位名"])%>
 
<%#DataBinder.eval_r(Container.DataItem,"欄位名","格式")%>


 
繫結到DataReader:
 
<%#((IDataReader)Container.DataItem).欄位名%>


 
當然為了方便一般使用最多的就是DataBinder類的Eval方法了.不過這樣對於同時要繫結大量的資料效率要低一些


在繫結資料時經常會用到這個句程式:<%# 
DataBinder.eval_r(Container.DataItem,"xxxx")%>
或者<%# 
DataBinder.eval_r(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)["欄位名"]%>


關鍵是Container這個東西,它比較神祕。它的名稱空間是System.ComponentModel。對於它我還需要進一步理解。


初學.NET,現在在看DataGrid控制元件,在ItemTemplate顯示資料時,
DataBinder.eval_r(Container.DataItem,"Name")和Container.DataItem("Name")有什麼區別?


DataBinder是System.Web裡面的一個靜態類,它提供了Eval方法用於簡化資料繫結表示式的編寫,但是它使用的方式是通過Reflection等開銷比較大的方法來達到易用性,因此其效能並不是最好的。而Container則根本不是任何一個靜態的物件或方法,它是ASP.NET頁面編譯器在資料繫結事件處理程式內部宣告的區域性變數,其型別是可以進行資料繫結的控制元件的資料容器型別(如在Repeater內部的資料繫結容器叫RepeaterItem),在這些容器類中基本都有DataItem屬性,因此你可以寫Container.DataItem,這個屬性返回的是你正在被繫結的資料來源中的那個資料項。如果你的資料來源是DataTable,則這個資料項的型別實際是DataRowView。
http://blog.csdn.net/jelink/article/details/1118839

相關文章