作者ThreeDay0905 (三天)
看板C_Sharp
标题Re: [问题] 自订class与GridView
时间Wed Sep 22 16:42:17 2010
※ 引述《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)
1F:推 dodoamuro:推一下 受教了!! 09/26 13:41