看板 C_Sharp 關於我們 聯絡資訊
※ 引述《dodoamuro (嘟嘟)》之銘言: : 最後寫出來了,分享給大家一下, : 就如同板友說的用ArrayList或List所產生的問題, : 是沒有將欄位定義,以及要使用GET及SET才會將資料寫入,所以加上 : <asp:Label ID="Label1" runat="server" Text='<%#Eval("Name") %>'></asp:Label> : 將欄位定義好,並使用get,set以後就可以了。 : 其中也跟好心的板友討論了一下,小弟才知道, : 原來GridView的DataSource,不是只能吃表格, : 而是只要有IList介面的都可以吃,真是學到了一課, : 之後一定要好好再把打NET練熟,也請各位多多指教! : 大家一起加油!!! 不只GridView可以吃, 其實像是CheckBoxList, RadioButtonList之類的控制項 都可以指定Class為DataSource 語法類似 ClassA[] arrA = new ClassA[10]; CheckBoxList1.DataSource = arrA; CheckBoxList1.DataTextField = "Property1"; CheckBoxList1.DataValueField = "Property2"; CheckBoxList1.DataBind(); 在DataBind的時候會自動去找尋Property1的值,指定為ListItem的Text Property2的值,指定為ListItem的Value 其他用法大同小異,假如說ClassA是放在Dictionary<int, ClassA>之中的話 那語法會變成 Dictionary<int, ClassA> hashTable = new Dictionary<int, ClassA>(); CheckBoxList1.DataSource = hashTable.Values; CheckBoxList1.DataTextField = "Property1"; CheckBoxList1.DataValueField = "Property2"; CheckBoxList1.DataBind(); 會發現差別只有DataSource不一樣,也就是說像現在很常用的LINQ匿名類別 也可以直接指定成為DataSource,再做DataBind 在GridView的用法也一樣, 可以在Template中的控制項中指定 Attr='<%#Eval("Property")%>' 或是直接把PropertyName指定給BoundField(or Other)的DataField 而比較進階的用法是可以在Bind的途中取回原有的物件再做處理 最常看到的就是在GridView的RowDataBound事件當中 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { ClassA objA = e.Row.DataItem as ClassA; int nIndex = e.Row.DataItemIndex; e.Row.Cells[2] = objA.Property1 + objA.Property2; //doSomething } 會發現在Bind的過程中可以在事件中抓回該行資料的DataSource再做應用 整個DataBind的流程大致如此 -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.249.135.130 ※ 編輯: ThreeDay0905 來自: 111.249.135.130 (09/22 20:36)
dodoamuro:推一下 受教了!! 09/26 13:41