星期四, 12月 03, 2009

動態聯繫 anonymous types 的 class

anonymous types 在 .net framework 3.5 才有的功能..我也常常用它來處理臨時資料的問題..一直覺得 anonymous types 是個好東西..今天寫程式的時候遇到了一個問題..就是要把 anonymous types 動態去塞入repeater 控制項內..忽然不知怎麼去處理..想了一下原來是腦袋打了結..休息一下..看看外面灰灰的天空..通啦..^^||..紀錄一下..

.aspx

<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Literal ID="litName" runat="server" />,
<asp:Literal ID="litUrl" runat="server" /><br />
</ItemTemplate>
</asp:Repeater>
</div>
</form>

.cs

protected void Page_Load(object sender, EventArgs e)
{
var data = new[] {
new{name="Bibby",url="http://bibby.be"},
new{name="Yahoo",url="http://tw.yahoo.com"},
new{name="Google",url="http://google.com"}
};

Repeater1.ItemDataBound +=
new RepeaterItemEventHandler(Repeater1_ItemDataBound);
Repeater1.DataSource = data;
Repeater1.DataBind();
}

void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
object o = e.Item.DataItem;
Literal litName = e.Item.FindControl("litName") as Literal;
Literal litUrl = e.Item.FindControl("litUrl") as Literal;

litName.Text = DataBinder.Eval(o, "name").ToString();
litUrl.Text = DataBinder.Eval(o, "url").ToString();
}

不過話說..DataBinder.Eval 方法在 msdn 裡面有說它校能不是很好啦..省著點用吧..

參考:

沒有留言: